Sub topic 1
CSS `:is()` and `:where()`: Grouping Selectors and Controlling Specificity
Prerequisites
You should know type, class, ID, and attribute selectors; combinators such as descendant and child; comma-separated selector lists; and the basic cascade. Specificity is the weight CSS uses to resolve competing declarations. It is commonly written as (IDs, classes, types).
The repetition problem with selector lists
Suppose links inside several heading levels should be underlined:
article h1 a,
article h2 a,
article h3 a {
text-decoration: underline;
}Every selector repeats article and a. Repetition makes a rule longer and makes later edits easier to miss. Adding h4 requires changing the list.
A quick specificity review
A selector's specificity has three main parts:
| Selector part | Example | Specificity contribution |
|---|---|---|
| ID | `#main` | `(1, 0, 0)` |
| Class, attribute, pseudo-class | `.note` | `(0, 1, 0)` |
| Type or pseudo-element | `p` | `(0, 0, 1)` |
Specificity is compared from left to right. An ID outweighs any number of classes, and a class outweighs any number of type selectors.
Matching alternatives with `:is()`
:is() groups alternative selectors inside one functional pseudo-class. It matches an element that matches at least one argument:
article :is(h1, h2, h3) a {
text-decoration: underline;
}This matches the same elements as the repeated rule. The surrounding selector is written once, so the rule is easier to read and extend.
:is() takes the specificity of its most specific argument. For example, :is(#main, .note) p has specificity (1, 0, 1), because #main is the strongest argument.
Matching alternatives with `:where()`
:where() has the same matching behavior as :is(), but it always contributes zero specificity:
:where(ul, ol) {
margin: 0;
padding-left: 1.5rem;
}This is useful for defaults. A later .menu rule can override it easily because :where() does not add selector weight.
Exercise
What specificity does :where(#main, .note) p have?
Show answer
(0, 0, 1). The :where() part contributes zero, and p contributes one type selector.