What is the CSS :has() selector and when to use it
· Category: HTML & CSS
Short answer
The CSS :has() pseudo-class is a relational selector that targets an element based on its descendants or adjacent siblings. It is often called the "parent selector" because it lets you style a parent when it contains a specific child.
Details
Before :has(), CSS could only style descendants or siblings in the forward direction. With :has(), you can write article:has(img) { ... } to style an article only when it contains an image. You can also target based on siblings, such as label:has(+ input:focus) to style a label when the next input is focused.
This selector is powerful for conditional layouts without JavaScript. For example, you can change a card's background when it contains a featured badge. When building these dynamic layouts, consider pairing them with CSS Grid auto-placement for intelligent item positioning.
Tips
:has()is supported in all modern browsers but can be expensive on very large DOM trees; use it thoughtfully.- It does not work in Firefox older than version 121; provide graceful fallbacks.
- For form UIs that rely on sibling states, you might also be interested in how to style HTML5 form validation messages for comprehensive form styling strategies.