:is() & :where()
Overview
Writing CSS for large applications often results in massive, unreadable comma-separated selector lists. If you want to style the h1, h2, and h3 tags inside header, main, and footer, the syntax explodes exponentially. The :is() and :where() pseudo-class functions solve this by acting like native CSS variables for selectors. They allow you to group multiple selectors together logically, drastically reducing file size and improving readability.
Syntax
/* --- THE OLD WAY --- */
header h1, header h2, header h3,
main h1, main h2, main h3,
footer h1, footer h2, footer h3 {
color: #333;
}
/* --- THE NEW WAY with :is() --- */
/* The browser automatically expands this matrix for you! */
:is(header, main, footer) :is(h1, h2, h3) {
color: #333;
}
/* --- THE NEW WAY with :where() --- */
/* Looks identical, but changes how Specificity works (See Pitfalls) */
:where(header, main, footer) :where(h1, h2, h3) {
color: #333;
}Common Pitfalls
- The 'Forgiving Selector' trap. If you write
header h1, header :invalid-pseudo, the entire block fails and theh1doesn't get styled. But if you write:is(header h1, header :invalid-pseudo), the browser forgives the error, ignores the invalid part, and successfully styles theh1. - Misunderstanding the Specificity math difference between
:is()and:where(). This is their primary difference!:is()adopts the specificity of the most powerful selector inside it.:where()always has a specificity score of ZERO (0,0,0).
Interview Questions
:where() instead of :is()?Because :where() guarantees a specificity score of 0. This means the reset styles are incredibly weak, making it effortless for developers to override them later without having to write aggressive, highly specific selectors.
Real-World Example
Aggressively reducing CSS bloat when styling markdown/CMS generated content.
/* Instead of writing 15 separate rules for prose content... */
.prose :is(p, ul, ol, blockquote, figure) {
margin-bottom: 1.5rem;
}
.prose :is(h1, h2, h3, h4) {
margin-top: 2rem;
font-weight: 700;
}Check Your Knowledge
Test your understanding of :is() & :where() with these quick questions.