CSS :has() Selector: Select Parent by Child
Selecting parent elements without JavaScript
Selecting a parent based on its children used to require JavaScript. :has() handles it in pure CSS, no event listeners needed.
The old hack vs the modern fix
View demo// Watch for changes, find parent
document.querySelectorAll('input')
.forEach(input => {
input.addEventListener('invalid', () => {
input.closest('.form-group')
.classList.add('has-error');
});
});.form-group:has(input:user-invalid) {
border-color: red;
background: #fff0f0;
}<!-- Tailwind v3.4+ has-[] variant --><div class="has-[input:user-invalid]:border-red-500 has-[input:user-invalid]:bg-red-50"> <input required /></div><!-- Card changes layout when it contains an image --><div class="has-[img]:grid has-[img]:grid-rows-[auto_1fr]"></div>Has browser support
Live demo
Why the modern way wins
No JavaScript needed
Eliminates an entire class of DOM-manipulation code. Fewer event listeners, fewer bugs.
Updates on its own
No event listeners to add or clean up. The browser re-checks the selector whenever the page changes.
Composes naturally
Chain with other selectors: .nav:has(.dropdown:hover), body:has(dialog[open]).
- Lines Saved
- 8 → 3
- JS → pure CSS
- Old Approach
- JavaScript
- Event listeners + DOM
- Modern Approach
- Pure CSS
- No event listeners
How it works
:has() is a relational pseudo-class. When you write .card:has(img), it selects any .card that contains an img as a descendant. It's the parent selector that CSS lacked for 25 years.
You can use any selector inside :has(): pseudo-classes like :invalid, :checked, :hover, or even combinators like :has(> .direct-child). It unlocks conditional styling that previously required JavaScript.
Two things to watch. The selector inside :has() counts toward specificity, so .card:has(img) p can beat rules you meant to win. Wrap it in :where() to drop that weight, or use :has(> img) to match direct children only. And a broad rule like body:has(.row.is-selected) makes the browser re-check a lot of the page on each change. One rule is usually fine. Measure before you stack several on a long list.