Skip to content
Web Design & Development

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.

MediaScaleUp Editorial Team 2 min read 7 views
The CSS :has() Selector Explained

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?

  1. Replace small JavaScript class toggles with :has() where possible
  2. Scope :has() selectors to specific components
  3. Provide acceptable styling where it is not supported if older browsers matter
  4. Test performance on large pages
  5. Combine with :focus-within and :checked for state styling
What to do and what to avoid with the CSS has() selector, side by side
Good practice against the usual mistakes, from the sources listed below.

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

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.

All services

The work behind this article, and what it costs.

MediaScaleUp Editorial Team

Articles here are researched, written and checked by the MediaScaleUp studio team before they are published, and dated when they are reviewed.

Keep reading

More in Web Design & Development