The CSS :has() Selector Explained
A relational pseudo-class that selects an element based on what it contains or what follows it, such as a card that contains an image or a form field with an invalid input.
On this page
Why does it matter?
It lets CSS style a parent or earlier sibling based on its contents, which previously required JavaScript.
What are the numbers?
- Syntax selector:has(relative selector)
- Example form:has(input:invalid) styles a form containing an invalid field
- Browser support all major browsers since late 2023
- Performance browsers optimize common uses, but very broad selectors can be costly
What should I do?
- Replace small JavaScript class toggles with :has() where possible
- Scope :has() selectors to specific components
- Provide acceptable styling where it is not supported if older browsers matter
- Test performance on large pages
- Combine with :focus-within and :checked for state styling
What should I avoid?
Avoid:
- Very broad selectors such as body:has() with complex conditions
- Replacing application logic with CSS tricks
- Assuming support in very old browsers
- Unreadable chains of relational selectors
When should I get help?
Short answer Bring in help when refactoring legacy JavaScript styling logic, or when designing component states.
Where this comes from
- MDN Web Docs — :has()
- Can I use — CSS :has() pseudo-class
The figures and practices above come from the sources listed.
Working on something like this?
We take on Web Design & Development work for teams who want it done once, properly. Tell us what you are building and we will tell you honestly whether we are the right studio for it. Start a project.
Where to go next
Spotted something wrong? Report an error on this page. We correct on the page and say what changed.