0
0
CssHow-ToBeginner · 3 min read

How to Use the :where() Selector in CSS for Simple Grouping

The CSS :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.

css
: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
/* CSS */
:where(h1, h2, p) {
  color: teal;
  font-family: Arial, sans-serif;
}

/* Additional style with higher specificity */
h1 {
  color: darkorange;
}
Output
All h1, h2, and p text is teal except h1 text which is dark orange.
⚠️

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.

css
/* Wrong: expecting high specificity */
:where(.btn, .link) {
  color: blue;
}

/* This can be overridden by */
.btn {
  color: red;
}
Output
Elements with class .btn will appear red, not blue, because :where() has zero specificity.
📊

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.

Key Takeaways

:where() groups selectors without increasing specificity.
Use commas inside :where() to list multiple selectors.
:where() styles can be easily overridden by more specific rules.
Ideal for applying base styles or grouping selectors simply.
Avoid complex selectors inside :where() for better browser support.