CSS :has() Patterns That Replace JavaScript

CSS :has() Patterns That Replace JavaScript

The relational selector retires the observer-and-class-toggle layer. Three worked pattern families, the scoping rule that keeps them cheap, and where JavaScript state still belongs.

Outside a few special cases such as :focus-within and :empty, a "style the parent based on the child" rule used to require a JavaScript observer and a class toggle. The relational pseudo-class :has() expresses that relationship directly in the stylesheet, and it has been supported in every core browser since December 2023 and is now Baseline Widely available — a safer deletion than several other recent CSS features that replace JavaScript, such as anchor positioning, CSS carousels, and customizable select, none of which had reached Baseline Widely available as of Nov 2026. This article works through the three pattern families that retire the most plumbing: form-state styling, quantity and content queries with their empty and populated states, and interaction patterns such as toggle-driven sections, plus the invalidation-scope rule that keeps them cheap and the honest line where JavaScript state management is still the right answer.

What :has() changes

CSS could always style downward. A selector could reach a descendant, a following sibling, an element in a particular position — but, apart from narrow cases such as :focus-within, never the container that held it, and never a preceding sibling. That single gap generated an enormous amount of code. A field wrapper that needs to look different when its input is invalid, a grid that needs a different column count when it holds four items instead of two, a card that lays out differently when it contains an image: each of those became an observer that watched the DOM and wrote a class onto the ancestor, plus the class in the stylesheet, plus the bookkeeping to keep the two in sync.

The shape of that workaround tended to look the same, whichever framework you were in. Something watched — an event handler, a mutation observer, a render pass, a reactive computed value — and something wrote a class name onto an ancestor. The stylesheet then keyed off the class rather than off the condition. Two representations of one fact, in two languages, updated by code you had to remember to run. When the two disagreed, the bug looked like a styling bug and was actually a synchronization bug, which is why they were so tedious to track down.

:has() closes the gap by making the relationship itself selectable. An element can now be styled by what it contains, what follows it, or what it relates to structurally — the engine evaluates the condition and applies the rule during selector matching, with nothing shipped to the client and no second copy of the state to keep in step.

Support is what sets this one apart from several other recent CSS features that replace JavaScript, such as anchor positioning, CSS carousels, or customizable select, none of which had reached Baseline Widely available as of Nov 2026. :has() has been supported in all core browsers since December 2023 and reached Baseline Widely available in June 2026 (web-features, accessed November 2026) — Firefox was the last to ship it. Verify against MDN or Baseline before you commit, since this paragraph ages; but if your support policy follows Baseline Widely available, the posture is plain adoption rather than adopt-with-fallback.

Form-state patterns

The first family styles a field wrapper from the state of the input inside it. One job validation libraries have taken on is writing .is-invalid onto a parent element, because the parent is what carries the border, the background tint, and the color of the label and hint text.

css
.field:has(:user-invalid) {
  --field-border: var(--color-danger);
}

.field:has(:user-invalid) .field-hint {
  color: var(--color-danger);
}

.field:has(input:disabled) {
  opacity: 0.6;
}

The wrapper reads the control's own state directly. No class is written, nothing listens for input events, and the styling cannot drift out of sync with the actual validity of the field because there is no second copy of the state to drift. (The timing question — why :user-invalid rather than :invalid — belongs to the form-primitives discussion; here it is simply the argument being passed in.)

The same shape covers the structural variations that used to need markup flags. A required marker driven by the attribute rather than a duplicated class:

css
.field:has([required]) .field-label::after {
  content: "*";
  color: var(--color-required);
}

And the float-label pattern, which historically needed a script to track whether the input was empty, expressed as an inversion of :placeholder-shown. It works only when the input has a placeholder attribute, because :placeholder-shown matches an input only while that attribute's value is being presented to the user; on an input without one, :not(:placeholder-shown) always matches and the label stays floated:

css
.field:has(input:not(:placeholder-shown)) .field-label,
.field:has(input:focus) .field-label {
  transform: translateY(-1.2em) scale(0.8);
}

Aggregations work at the form level too — a submit area that reflects whether any control in the form is currently invalid — but keep an eye on the scope of the subject, which the performance section returns to.

Quantity and content queries

The second family styles a container by how many children it has, or by what kind of children they are. Before :has(), both were counted in JavaScript and written back as a class.

The counting idiom combines :has() with :nth-child(): a container that contains a child at position four or later necessarily has at least four children.

css
/* three or fewer items: single row */
.toolbar {
  display: flex;
  gap: 0.5rem;
}

/* four or more: wrap into a grid */
.toolbar:has(> :nth-child(4)) {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

Empty and populated states are the same idea at its simplest, and they retire the is-empty class a list component would otherwise maintain:

css
.tag-list:not(:has(*)) {
  display: none;
}

.results:not(:has(.result)) .empty-message {
  display: block;
}

A caution worth carrying into the counting idiom: it asks whether a child exists at a given position, so the thresholds compose the way you would expect only if you keep them in one direction. Layering "four or more" on top of "six or more" means two rules can match at once, and the winner is decided by ordinary cascade rules rather than by whichever range you had in mind. Writing the ranges as an ascending sequence of overrides, the way you would with media queries, keeps that legible.

Content-shape adaptation follows naturally. A card that contains a figure gets a two-column layout; the same card with text only stays single-column — one rule, no variant class threaded through the template:

css
.card:has(> figure) {
  display: grid;
  grid-template-columns: 12rem 1fr;
  gap: 1.5rem;
}

Interaction patterns

The third family reaches across siblings. Dimming every item in a list except the one under the cursor was, until recently, a pair of mouseenter and mouseleave handlers writing a class onto the container:

css
.list:has(.item:hover) .item:not(:hover) {
  opacity: 0.55;
}

Toggle-driven sections are the old checkbox hack made legible. The state still lives in a real form control — which is what keeps it keyboard-accessible and announced by assistive technology — but the styling no longer has to be expressed through sibling-combinator contortions that constrain the markup order:

css
.panel:has(#advanced-toggle:checked) .advanced-options {
  display: block;
}

.panel:has(#advanced-toggle:checked) .summary-view {
  display: none;
}

And container-level focus treatments go beyond what :focus-within could express, because the argument can be as specific as you need:

css
.card:has(:focus-visible) {
  outline: 2px solid var(--color-focus);
  outline-offset: 4px;
}

That last one is a genuine capability difference rather than a convenience: :focus-within matches keyboard and pointer focus alike, while this rule fires only for the focus states the engine considers worth showing a ring for.

Performance and honest limits

The cost model is worth understanding precisely, because it produces one rule that matters and a lot of folklore that does not.

When a rule uses :has(), the engine must re-evaluate the subject element whenever something inside the tested scope changes. The practical consequence is mostly about scope — both the subject the rule is anchored to and how far the argument has to search: .field:has(:user-invalid) re-checks a small subtree when that field changes, while body:has(.modal-open) puts the entire document in play on every mutation anywhere in it. Keep subjects tight and close to the elements being tested, and keep the argument tightly constrained — combinators such as > or + limit how far the engine has to traverse when something changes. Where a document-level state genuinely is what you need — a class on a wrapper set once when a modal opens — a plain class is still a perfectly good tool, and reaching for :has() to avoid it is not a virtue.

Two structural limits shape how the patterns compose. :has() cannot be nested inside another :has(), so conditions that would need a relational test inside a relational test have to be restructured or resolved in markup. And specificity is taken from the most specific selector in the argument list, the same way :is() and :not() behave — so .card:has(#featured) carries an ID's weight, which is an easy way to create a cascade problem you did not intend (MDN, accessed November 2026; the relational pseudo-class is specified in Selectors Level 4).

The honest line is the one worth remembering when the patterns start feeling universal. :has() reads DOM state; it does not manage state. Anything that has to persist across a reload, synchronize with a server, or survive navigation is application state and belongs where application state lives. Anything that has to coordinate across unrelated subtrees — a sidebar reacting to something in a modal three containers away — will either not be expressible or will require a document-level subject you should be wary of. And anything with more than a couple of positions is a state machine, not a selector: once you find yourself encoding three or four modes in nested relational conditions, the stylesheet has stopped being the honest place for it.

Project Inquiry