CSS :has() Relational Selector
:has() is a relational pseudo-class that styles a parent or preceding sibling based on what it contains or precedes. It eliminates MutationObserver hacks and manual .has-error class toggling while staying reactive to live DOM state.
JS MutationObserver/Class Toggle vs CSS :has()
Compare imperative parent class syncing against declarative :has() styling.
document.querySelectorAll('.card').forEach((card) => {
if (card.querySelector('img')) {
card.classList.add('card--with-media');
}
});Requires re-running whenever cards hydrate or mutate.
.card:has(> img) {
grid-template-columns: 120px 1fr;
gap: 1rem;
}Evaluated natively during Style resolution on any DOM change.
Under the Hood
For twenty years CSS only looked downward and forward because engines feared O(n^2) re-evaluations during the Browser Rendering Pipeline. Modern engines solved this with bloom-filter fast-rejects and targeted invalidation flags.
- Right-to-Left Anchoring: When a child changes (e.g., a checkbox becomes
:checked), the engine checks an ancestor bitmask to see if any parent listens to:has(). - Specificity: Like
:is(),:has()adopts the highest Specificity in its argument list unless wrapped in:where(). - Sibling Lookahead:
.tab:has(+ .tab:hover)styles the element before the hovered sibling.
/* Highlight form field label when its input is invalid and touched */
.field:has(input:user-invalid) > label {
color: #dc2626;
}
/* Lock page scroll when a modal checkbox or dialog is open */
body:has(dialog[open]) {
overflow: hidden;
}Problem Genealogy
- 2000–2021: Rejected repeatedly due to layout-engine invalidation cost; developers toggled parent classes in JS or React state.
- 2022–2023: Safari, Chrome, and Firefox shipped optimized
:has()with invalidation bitmasks, reaching Baseline Newly Available.
Production Pitfalls
:root:has(...)over-invalidation: Attaching:has()to:rootorbodywith broad selectors like:has(*:hover)triggers wide style recalculations on pointer moves.- Nesting
:has(:has(...)): Nested:has()is disallowed by the spec and silently ignored.
- When not to use
:has(): Avoid:has()on:rootfor high-frequency hover/scroll states; scope it to small local components like.fieldor.card.
Connections & Logical Next Steps
:has() inherits the highest specificity among its relative selector arguments.
Uses ancestor invalidation bitmasks and bloom filters during Recalc Style to avoid O(n^2) matching.
:has() adopts the highest specificity of its relative selector list instead of summing combinators.