What is the CSS :has() selector and how to use it
· Category: HTML & CSS
Short answer
:has() is a relational pseudo-class that selects an element if it contains a descendant matching the given selector. It acts like a parent selector.
How it works
Unlike most selectors that target descendants, :has() targets ancestors based on their contents. It enables complex conditional styling without extra classes or scripts.
Example
/* Style a card that contains an image */
.card:has(img) {
display: flex;
gap: 1rem;
}
/* Style a label when its input is focused */
label:has(input:focus) {
color: blue;
}
Tips
- Use it sparingly; complex
:has()chains can impact performance. - Browser support is strong in modern versions of Chrome, Safari, and Firefox.
- It is a great replacement for JavaScript-driven conditional class toggling.