How to Use the :where() Selector in CSS for Simple Grouping
:where() selector lets you group multiple selectors without increasing specificity, making it easier to write flexible styles. Use it by placing selectors inside :where() parentheses, separated by commas, like :where(h1, h2, p).Syntax
The :where() selector takes a list of selectors inside parentheses, separated by commas. It matches any element that fits any of the selectors inside.
Example parts:
:where()- the selector function- Inside parentheses - one or more selectors separated by commas
This selector always has zero specificity, so it won't override other styles with the same selectors but higher specificity.
:where(selector1, selector2, selector3) {
/* CSS rules here */
}Example
This example shows how to style all h1, h2, and p elements with the same color using :where(). It keeps specificity low, so other styles can override it easily.
/* CSS */ :where(h1, h2, p) { color: teal; font-family: Arial, sans-serif; } /* Additional style with higher specificity */ h1 { color: darkorange; }
Common Pitfalls
One common mistake is expecting :where() to increase specificity like grouping selectors normally does. It does not add specificity, so styles inside :where() can be easily overridden.
Another pitfall is using :where() with complex selectors that might confuse browser support or cause unexpected matches.
/* Wrong: expecting high specificity */ :where(.btn, .link) { color: blue; } /* This can be overridden by */ .btn { color: red; }
Quick Reference
- :where() groups selectors without adding specificity.
- Use commas to separate selectors inside parentheses.
- Always zero specificity, so it won't override more specific rules.
- Great for base styles or resetting styles.