Pseudo- classes in CSS: Adjusting Selector Specificity with :where()

The CSS Selectors Level 4 specification calls :where() the “specificity-adjustment pseudo­class”. It’s also a functional pseudo-class that accepts a selector or a selector list as its argument. Using :where() limits the impact of a selector’s specificity without changing it.

Consider this CSS snippet:

a:not( :hover ) { /* Specificity of 0,1,1 */

text-decoration: underline 2px;

}

nav a { /* Specificity of 0,0,2. This rule does not take effect */

text-decoration: hsl( 340, 82%, 52% ) wavy underline 1.5px;

}

In this example, our first rule has a more specific selector than our second. As a result, the second rule is never applied, and the links don’t get a wavy, pink underline.

One way to resolve this would be to change nav a to nav a:not(:hover) . Doing so would increase the specificity of that rule, which may not be what you want. Let’s try :where() instead:

a:where( :not( :hover ) ) { /* Retains specificity of 0,1,1 but with an adjustment */

text-decoration: underline 2px;

}

nav a { /* Rule takes effect. Still has a specificity of 0,0,2 */

text-decoration: red wavy underline 1.5px;

}

Adding :where() says to the browser: “Apply this style to <a> elements only where they don’t have a hover state.” Now our navigation links have squiggly underlines.

Again, using :where() doesn’t modify the specificity value of a selector. In fact, its specificity value is zero. Instead, think of it as a way to clarify your intent.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *