Home > Web Front-end > CSS Tutorial > Why Does My `.foo a:link` and `.foo a:visited` CSS Override `a:hover` and `a:active`?

Why Does My `.foo a:link` and `.foo a:visited` CSS Override `a:hover` and `a:active`?

Susan Sarandon
Release: 2024-11-28 14:03:12
Original
697 people have browsed it

Why Does My `.foo a:link` and `.foo a:visited` CSS Override `a:hover` and `a:active`?

Why Does .foo a:link, .foo a:visited Selector Override a:hover, a:active Selector in CSS?

The unexpected behavior described in the question arises from the specificity rules of CSS. Specificity determines the precedence of CSS rules when multiple rules apply to the same element.

Specificity Table:

Selector Specificity
a:link 0-0-1-1
a:visited 0-0-1-1
a:hover 0-0-1-1
a:active 0-0-1-1
.foo a:link 0-0-2-1
.foo a:visited 0-0-2-1

As you can see, .foo a:link and .foo a:visited have slightly higher specificity than a:hover and a:active due to the additional class selector .foo.

How Specificity Override Works:

When multiple rules with different specificities apply to the same element, the rule with the higher specificity takes precedence. In this case, .foo a:link and .foo a:visited have higher specificity than a:hover and a:active, so their styles override those of the latter.

Correcting the Behavior:

To prevent the .foo a:link, .foo a:visited selector from overriding a:hover, a:active, you can increase the specificity of the latter. This can be achieved by adding a child selector to the hover/active rules:

.foo a:hover, .foo a:active {
  color: red;
}
Copy after login

By adding the .foo class as a child selector, the specificity of the hover/active rules increases to 0-0-3-1, which is higher than that of .foo a:link and .foo a:visited. As a result, the hover/active styles will have precedence and take effect over the link/visited styles when both pseudo-classes are applicable.

The above is the detailed content of Why Does My `.foo a:link` and `.foo a:visited` CSS Override `a:hover` and `a:active`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template