/* Style a form only when it contains an invalid field */
form:has(:invalid) {
border-color: var(--error);
}
/* Style a card differently when it contains an image */
.card:has(img) {
padding-top: 0;
}
A genuine gap in CSS, finally closed
Selectors have always been able to describe descendants and siblings, but never a parent based on its own children - that asymmetry is exactly what :has() fixes, and it removes a real category of JavaScript that used to exist purely to toggle a class based on DOM structure.
A practical pattern we've adopted
.nav-item:has(> .submenu) {
/* style differently when this item has a dropdown */
}
Worth a note of caution
:has() can be written in ways that are expensive for the browser to evaluate on very large, deeply nested pages. On most typical component-level use it's a non-issue - just worth testing on a page with unusually heavy DOM before relying on it broadly.
Styling a parent based on its children - finally
Every prior version of CSS could select a child based on its parent, never the reverse. That gap forced a lot of unnecessary JavaScript just to toggle a class on a container when one of its children matched some condition. :has() closes it directly in CSS:
/* Style a form group only when it contains an invalid input */
.form-group:has(input:invalid) { border-color: red; }
/* Style a card differently when it has an image */
.card:has(img) { grid-template-columns: 120px 1fr; }
It's really a general-purpose "if" for CSS
Because :has() accepts any selector inside it - including combinators like + and ~ - it effectively adds conditional logic to the cascade: style this element differently based on what's near it, what it contains, or what state its descendants are in. It's one of the rare CSS features that removes JavaScript from a codebase rather than adding a new dependency.