Modern CSS Selectors: :where(), :is(), and :has()
CSS continues to evolve, introducing powerful new selectors that enhance styling capabilities.
Three new selectors are :is()
, :where()
, and :has()
.
The :is() Selector
It helps simplify complex selectors by grouping multiple elements.
Example:
nav > ul a:hover,
footer > ol a:hover,
aside > p a:hover {
color: purple;
}
/** Can become **/
:is(nav > ul, footer > ol, aside > p) a:hover {
color: purple;
}
The :where() Selector
The :where() selector does the same as :is() without increasing specificity. This makes it useful for defining styles without affecting existing styles priority.
This can help you escape out of issues where your only recourse would've been an even more specific selector or adding an !important to a CSS rule.
While useful for specificity issues, there is another area where the :where() pseudo class can have a big impact: in CSS libraries.
Key Takeaway:
- Use :is() when you need specificity to be retained.
- Use :where() when you want to apply styles without increasing specificity, making it easier to override with other CSS rules.
The :has() Selector
The :has() selector, often called the "parent selector," allows you to style elements based on the presence of specific child elements. This was previously impossible with pure CSS.
Example:
article:has(img) {
border: 2px solid red;
}
This applies a red border to any article that contains an img.
Conclusion
These new selectors :where(), :is(), and :has() bring more power and flexibility to CSS. :where() minimizes specificity, :is() simplifies complex selectors, and :has() enables parent-based styling.