CSS & LayoutBaseline · Newly

CSS :has() Relational Selector

Mental Model

: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.

Interactive Simulator

JS MutationObserver/Class Toggle vs CSS :has()

Compare imperative parent class syncing against declarative :has() styling.

Lines of Code
Before
5
After
4
Reflows / Browser Cost
Before
Extra DOM write pass
After
0 extra passes
BeforeJS Parent Class Sync
document.querySelectorAll('.card').forEach((card) => {
  if (card.querySelector('img')) {
    card.classList.add('card--with-media');
  }
});
Lines: 5Reflows: Extra DOM write passDependencies: JS query + class sync

Requires re-running whenever cards hydrate or mutate.

After (Native)Native CSS :has()
.card:has(> img) {
  grid-template-columns: 120px 1fr;
  gap: 1rem;
}
Lines: 4Reflows: 0 extra passesDependencies: 0 JS

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.

  1. 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().
  2. Specificity: Like :is(), :has() adopts the highest Specificity in its argument list unless wrapped in :where().
  3. Sibling Lookahead: .tab:has(+ .tab:hover) styles the element before the hovered sibling.
CSS
/* 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

Production Pitfall
  • :root:has(...) over-invalidation: Attaching :has() to :root or body with 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
  • When not to use :has(): Avoid :has() on :root for high-frequency hover/scroll states; scope it to small local components like .field or .card.

Connections & Logical Next Steps

CSS & LayoutCSS :has() Relational Selector

Mechanical Comparisons