Specificity Conundrum: Why .foo a Selector Overrules a:hover, a:active
CSS specificity dictates how styles are applied based on selector weight. In the problem given, the .foo a selector conflicts with a:hover and a:active.
Understanding Specificity
Specificity is determined by the number of tags, classes, and IDs in a selector, with each level holding a specific weight. In this case, the specificity table provided shows that .foo a:link and .foo a:visited have a higher specificity (0 0 2 1) than a:hover and a:active (0 0 1 1).
Why .foo a Overrides
The .foo a selector is more specific than a:hover and a:active because it applies to links within elements with the foo class. When an element meets multiple selectors with the same specificity, the last declared style is applied.
Correcting .foo a Selector
To allow the a:hover and a:active styles to take precedence, the .foo a selector must be modified to have a lower specificity. One possible fix is:
.foo a:hover, .foo a:active { color: red; }
By adding .foo before the hover and active pseudo-classes, the specificity remains higher than a:hover and a:active, ensuring that the styles for those pseudo-classes are applied within elements with the foo class.
Takeaway
Specificity determines how CSS styles are applied. Understanding this concept is crucial for controlling style precedence and achieving the desired visual effect.
The above is the detailed content of Why Does `.foo a` Override `a:hover` and `a:active` in CSS Specificity?. For more information, please follow other related articles on the PHP Chinese website!