Sub topic 2
How `:is()` and `:where()` Differ in Specificity
Assume you know basic selectors, combinators, selector lists, and how the cascade resolves conflicts. The key difference is specificity, the weight CSS uses when competing declarations have the same origin and importance.
`:is()` Uses the Most Specific Argument
:is() groups alternatives without repeating the surrounding selector. Its specificity equals the most specific selector inside its parentheses, plus the specificity of the rest of the selector.
Specificity is commonly written as (IDs, classes, types):
/* Both rules match links inside h1, h2, and h3 elements. */
article h1 a,
article h2 a,
article h3 a {
text-decoration: underline;
}
article :is(h1, h2, h3) a {
text-decoration: underline;
}
/* :is(#main, .note) contributes (1, 0, 0), from #main. */
:is(#main, .note) p {
color: blue;
}
/* :where() contributes (0, 0, 0). */
:where(#main, .note) p {
color: blue;
}In the second example, :is(#main, .note) p has specificity (1, 0, 1). The ID wins even when the element matches .note.
Cutting Repetition in Real Stylesheets
Use :is() when several alternatives share the same context or declaration:
.card :is(h2, h3, h4) a {
color: rebeccapurple;
}This is easier to maintain than three repeated selectors. Adding another heading only requires changing the argument list.
Writing Defaults That Are Easy to Override
Use :where() for broad defaults, especially in reusable components or base styles. It always contributes zero specificity:
:where(ul, ol) {
margin: 0;
padding-left: 1.5rem;
}
.menu {
padding-left: 0;
}The .menu rule has specificity (0, 1, 0), so it overrides the :where() rule regardless of source order, assuming equal cascade layers and importance.
Choosing Between `:is()` and `:where()`
| Goal | Choose | Reason |
|---|---|---|
| Group alternatives while preserving normal selector strength | `:is()` | It uses the most specific argument |
| Provide a reset or default style | `:where()` | It adds no specificity |
| Avoid repeated contextual selectors | Either | Both reduce repetition |
Exercise
What specificity does :is(#hero, .banner) p have, and what specificity does :where(#hero, .banner) p have?
Show answer
The :is() selector has (1, 0, 1), while the :where() selector has (0, 0, 1).