Sub topic 2
Specificity of `:is()`, `:where()` and `:not()`
Assume you know HTML nesting, classes, IDs, basic CSS rules, and how to inspect an element in browser developer tools. This chapter focuses on how selector functions affect the cascade.
Specificity functions
Specificity is a score that helps CSS choose between matching declarations. It has three parts:
- IDs, such as
#menu - Classes, attributes, and pseudo-classes, such as
.activeand:hover - Elements and pseudo-elements, such as
buttonand::before
The :is(), :not(), and :has() pseudo-classes take the specificity of their most specific argument. The pseudo-class itself does not add another point. :where() is different: it always contributes zero specificity, including the selectors inside it.
:is(#app, .panel) button { color: blue; } /* (1,0,1) */
:where(#app, .panel) button { color: red; } /* (0,0,1) */
.card:not(.disabled) { opacity: 1; } /* (0,2,0) */The :is() selector can therefore become unexpectedly strong when one alternative contains an ID. Use :where() for defaults that should be easy to override.
Source order: the last rule wins a tie
If declarations have equal origin, importance, layer, and specificity, CSS uses source order. The declaration that appears later wins.
.button { background: gray; }
.button { background: steelblue; }Both selectors score (0,1,0), so the button is steelblue.
Cascade layers with `@layer`
Cascade layers provide an earlier precedence decision than specificity. For normal declarations, a later layer wins over an earlier layer, even if its selector is less specific.
@layer base, components;
@layer base {
#nav a { color: navy; }
}
@layer components {
a { color: teal; }
}The link is teal because components comes after base. This lets you override framework styles without creating increasingly specific selectors. Important declarations reverse the layer order, so reserve !important for deliberate exceptions.
From declared to used values
A declaration is the value written in CSS. The browser processes it into stages:
- The specified value is the result after the cascade and keyword handling.
- The computed value resolves inheritance and many relative values.
- The used value is the value applied during layout, after context such as available width is known.
For example, width: 50% may compute as 50%, but its used value depends on the containing block's width.
Exercise
Which rule makes the link red, and why? :where(#nav) a { color: blue; } a { color: red; }
Show answer
The second rule wins. Both selectors have element specificity (0,0,1) because :where() contributes zero, so source order selects the later rule.