The Cascade ·

Style the parent with :has()

CSS finally lets an element react to what's inside it. No JavaScript, no toggled classes.

  • #selectors
  • #has
For years the answer to “can CSS select a parent?” was no, so we wrote JavaScript to toggle an .is-selected class. :has() makes that class unnecessary: the parent can check its own contents.
Live examplePoint at anything to see its CSS
/* The card that contains the checked radio */
.plan:has(input:checked) {
  border-color: #1a1a1a;
  box-shadow: 0 0 0 3px #1a1a1a;
}/* Once anything is picked, fade the rest */
.plans:has(input:checked) .plan:not(:has(input:checked)) {
  opacity: 0.55;
}

The whole technique

A:has(B) matches any A that contains something matching B. In the demo, each plan card wraps a radio button, and the card that holds the checked one gets a ring:

.plan:has(input:checked) {
  border-color: #1a1a1a;
  box-shadow: 0 0 0 3px #1a1a1a;
}

Click a plan and the style follows. The browser rechecks the selector whenever the DOM or an element's state changes, so there's nothing to wire up.

Reach sideways, too

The argument is a relative selector, so it can start with a combinator. h2:has(+ p) matches a heading followed directly by a paragraph. The demo also uses the container to fade the cards that weren't picked:

.plans:has(input:checked) .plan:not(:has(input:checked)) {
  opacity: 0.55;
}

Read it as: inside a group where something is checked, dim every plan that isn't the checked one.

More places it pays off

  • Form validation: .field:has(input:user-invalid) turns the whole field, label included, red after the user has interacted with it.
  • Optional media: .card:has(img) switches a card to a two-column layout only when it has an image.
  • Scroll locking: body:has(dialog[open]) sets overflow: hidden while a modal is open.

Things to know

  • You can't nest :has() inside another :has(), and pseudo-elements aren't allowed in the argument.
  • Its specificity is that of its most specific argument, just like :is(). .plan:has(#pro) carries ID-level weight.
  • Anchor it to a specific element. .plan:has(…) only has to look inside plans; a bare :has(…) asks the browser to check every element on the page.
  • It has worked in every major browser since December 2023 (Firefox was last, in version 121).