DEV Community

Cover image for The CSS :has() Selector — The Parent Selector We Waited Years For
Pawar Shivam
Pawar Shivam

Posted on

The CSS :has() Selector — The Parent Selector We Waited Years For

=> Why Targeting Parent Was Always Hard

Before this, CSS could only go downward:

.parent .child {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

But you couldn’t do:

👉 style parent based on child


=> The Game-Changer: :has()

Now you can:

.card:has(img) {
  border: 2px solid green;
}
Enter fullscreen mode Exit fullscreen mode

👉 If .card contains an image → style it


=> Real Power Example

Form validation:

.form-group:has(input:invalid) {
  border: 1px solid red;
}
Enter fullscreen mode Exit fullscreen mode

👉 No JavaScript needed


=> Interactive UI Without JS

.button:has(:hover) {
  background: black;
}
Enter fullscreen mode Exit fullscreen mode

Or:

.menu:has(.active) {
  display: block;
}
Enter fullscreen mode Exit fullscreen mode

=> Why This Is Big

You can now:

  • reduce JavaScript
  • write cleaner CSS
  • build smarter UI logic

=> What Developers Often Miss

This is not just a selector.

👉 It’s conditional logic in CSS


=> Performance Note

:has() can be expensive if overused.

Avoid:

*:has(.child)
Enter fullscreen mode Exit fullscreen mode

👉 Too broad = slow


=> Browser Support

Now supported in modern browsers.

But always test before production.


=> Real UI Tip

Use :has() for:

  • form states
  • conditional styling
  • parent-based layouts

=> What Do You Think?

Will :has() reduce the need for JavaScript in UI logic?

Top comments (0)