Parent-Aware Layouts With :has(): Letting Containers React to Their Contents

For most of CSS's history, styling flowed one way: an element could be styled by its ancestors, its own classes and its earlier siblings, but never by anything inside it or after it. Layouts that depended on content — a card that needs a different grid when it has an image, a list that should switch to columns when it grows long, a form group that should highlight when its input is invalid — needed JavaScript or a template to translate content into classes. :has() removed that restriction. This guide, part of Mastering Container Queries & Responsive Layouts, treats :has() specifically as a layout tool: how its matching works, which patterns it unlocks, how it interacts with the cascade and container queries, and what to watch for in production.

Prerequisites — this guide assumes you can already:

  • Read compound and complex selectors, including the child (>), next-sibling (+) and subsequent-sibling (~) combinators.
  • Calculate selector specificity as an (ID, class, type) triple.
  • Build a basic grid or flex layout (see CSS Grid & Subgrid Layouts).
  • Use @supports for progressive enhancement.

The Core Concept: A Relational Pseudo-Class

The Selectors Level 4 specification defines :has() as a relational pseudo-class: it takes a list of relative selectors and represents an element if any of those selectors, when anchored at that element, matches at least one element. "Anchored" is the key word. The relative selector > img anchored at a .card means "an img that is a child of this card". The relative selector + .error means "an .error that is this element's next sibling". The relative selector with no leading combinator, such as img, is treated as a descendant relation.

What makes this significant for layout is which element is the subject. In .card:has(> img), the declarations apply to .card, not to the image. For the first time, a rule can change a container's display, grid-template-*, flex-direction or gap based on facts about its children.

What a :has() argument can reach An anchor element in the centre. Descendant form reaches any element inside it, child form reaches only direct children, next-sibling form reaches the immediately following sibling, and subsequent-sibling form reaches any later sibling. Four directions from one anchor anchor :has(> x) child wrapper :has(x) deep :has(+ x) next :has(~ x) later In every case the anchor is the element that gets styled. The argument is only a condition evaluated from it.

Layout questions :has() can now answer

Grouping the practical uses by the question they answer makes the feature easier to reach for at the right moment:

  • How many children are there? Combined with :nth-child(), :has() becomes a quantity query that changes a container's layout at a child count — covered in Quantity Queries With ().
  • Which kinds of children are there? A card can add a media row only when it has media and a footer row only when it has actions — covered in Content-Aware Card Layouts With ().
  • What state are the controls in? A form group can react to a checked, invalid or focused input — covered in Form Validation Layouts With ().
  • What comes next? A heading followed immediately by a subtitle can tighten its bottom margin with h2:has(+ .subtitle), the long-requested "previous sibling" selector.

The two remaining guides in this section deal with the costs and alternatives: () Selector Performance explains invalidation and what keeps it cheap, and () vs Container Style Queries compares discovered state with published state.

What it replaced

It helps to remember what each of these patterns used to cost, because many codebases still carry the old versions. Content-dependent card layouts were modifier classes computed in the template. Quantity queries existed only in the item-styling form, li:nth-last-child(n+4) ~ li, which could never touch the list. Form-group state was a focusin/input listener copying validity onto a class. And "style the element before this one" was simply impossible: designers were told to restructure the markup so the thing that needed styling came after the thing it depended on.

Each workaround moved layout knowledge out of the stylesheet — into templates, scripts or markup order — and each could fall out of sync with the content it described. The consistent benefit of :has() is that it moves that knowledge back, next to the rules that use it, and makes it impossible to go stale. When auditing an older codebase, searching for class names containing --has-, --with-, --no- or --count- is a quick way to find candidates.

Specificity: the trap in the argument

:has() behaves like :is() and :not() for specificity: it contributes the weight of its most specific argument and nothing of its own. That is usually harmless, but it makes the weight of a rule depend on something that reads like a condition rather than a target, which surprises people.

How :has() arguments change a rule's weight .card is 0,1,0. .card:has(.media) is 0,2,0. .card:has(#promo) is 1,1,0 and outranks both. :where(.card:has(#promo)) is 0,0,0. The argument sets the weight .card (0, 1, 0) .card:has(.media) (0, 2, 0) .card:has(#promo) (1, 1, 0) wins :where(.card:has(#promo)) (0, 0, 0) An ID inside the argument outranks any number of classes on the subject.

Two habits keep this under control. Prefer classes and attributes inside :has() arguments, never IDs, so the weight stays in the same band as the rest of a component's rules. And when a :has() rule is meant to be a low-priority default that anything can override, wrap it in :where(), which zeroes the specificity entirely. Cascade layers are the structural alternative: place enhancement rules in a layer and their precedence is decided by layer order rather than by what happens to be inside the parentheses.


Syntax and Parameters

TokenAccepted valuesDefault / notes
:has( <relative-selector-list> )One or more relative selectors, comma-separatedNo default; an empty argument is invalid
Leading combinatornone (descendant), >, +, ~Omitted means descendant
Argument contentsAny selector except :has() itself and pseudo-elementsNesting :has() is disallowed
Forgiving parsingNot forgiving: one invalid selector invalidates the listWrap uncertain parts in :is() to make them forgiving
SpecificityThat of the most specific argumentThe pseudo-class adds nothing itself
Negation:not(:has(...))Standard way to express absence
Composition:has(a):has(b)Both conditions must hold

The forgiving-parsing row matters in practice. :has(:user-invalid, :invalid) in an engine that does not recognise :user-invalid invalidates the entire selector, not just that branch. Writing :has(:is(:user-invalid, :invalid)) uses :is()'s forgiving list, so the unknown branch is ignored and the known one still works.


Step-by-Step Implementation: A Settings Panel That Reacts to Its Contents

The steps below build one panel that uses each direction of :has() in turn.

Step 1: a baseline layout without :has()

.settings {
  display: grid;
  gap: 1rem;
  padding: 1.25rem;
  border: 1px solid #cbd5e1;
  border-radius: 12px;
}

.settings__row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 0.5rem 1rem;
}

This baseline is complete: every browser renders a usable panel from it. Everything that follows is an enhancement layered on top.

Step 2: react to how many rows exist

/* Five or more rows: split into two columns when there is room. */
.settings:has(> .settings__row:nth-child(5)) {
  grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
}

Step 3: react to control state

/* A row whose toggle is off is visually de-emphasised. */
.settings__row:has(input[type="checkbox"]:not(:checked)) .settings__label {
  color: #64748b;
}

/* When the master switch is off, the whole panel dims its other rows. */
.settings:has(#master-switch:not(:checked)) > .settings__row:not(:has(#master-switch)) {
  opacity: 0.5;
}

Step 4: react to what follows

/* A row immediately followed by a help paragraph loses its bottom
   border so the two read as one unit. */
.settings__row:has(+ .settings__help) {
  border-bottom: 0;
  padding-bottom: 0;
}

Step 5: guard the enhancements

@supports not selector(:has(*)) {
  /* Engines without :has(): keep the help paragraph visually attached
     with a negative margin instead of the border change above. */
  .settings__help { margin-top: -0.5rem; }
}

Each step's rule is independent, so a problem in one — say, a mistaken ID in step 3 — does not affect the others. That independence is what makes :has() enhancements safe to add incrementally to an existing component.


Annotated Production Example: A Pricing Plan Picker

The component below is a set of radio-button cards. Every visual reaction — the selected card's emphasis, the summary text, the call-to-action label — is driven by which radio is checked, with no script.

Live demoPlan picker driven by the checked radio
Click a plan or use the arrow keys: the card, the summary line and the focus ring all follow the checked radio. Drag the bottom-right corner to resize the frame in either direction.
<form class="plans">
  <fieldset class="plans__options">
    <legend>Choose a plan</legend>
    <label class="plan">
      <input type="radio" name="plan" value="starter" checked>
      <span class="plan__name">Starter</span>
      <span class="plan__price">$9/mo</span>
    </label>
    <label class="plan">
      <input type="radio" name="plan" value="team">
      <span class="plan__name">Team</span>
      <span class="plan__price">$29/mo</span>
    </label>
    <label class="plan">
      <input type="radio" name="plan" value="scale">
      <span class="plan__name">Scale</span>
      <span class="plan__price">$99/mo</span>
    </label>
  </fieldset>
  <p class="plans__summary"></p>
  <button class="plans__cta" type="submit">Continue</button>
</form>
.plans__options {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr));
  gap: 0.75rem;
  margin: 0;
  padding: 0;
  border: 0;
}

.plan {
  display: grid;
  gap: 0.25rem;
  padding: 1rem;
  border: 2px solid #cbd5e1;
  border-radius: 12px;
  cursor: pointer;
  transition: border-color 0.15s ease, transform 0.15s ease;
}

/* The card is the subject; the checked radio inside it is the condition. */
.plan:has(input:checked) {
  border-color: #4f46e5;
  transform: translateY(-2px);
}

/* Keyboard focus lands on the visually small radio; surface it on the card. */
.plan:has(input:focus-visible) {
  outline: 2px solid #4f46e5;
  outline-offset: 3px;
}

/* The form reads the same state to write a summary and relabel the CTA. */
.plans__summary::before { content: "Starter: for one person."; }
.plans:has(input[value="team"]:checked) .plans__summary::before { content: "Team: up to 10 seats."; }
.plans:has(input[value="scale"]:checked) .plans__summary::before { content: "Scale: unlimited seats and SSO."; }

@media (prefers-reduced-motion: reduce) {
  .plan { transition: none; }
  .plan:has(input:checked) { transform: none; }
}

The radios remain real, visible form controls, so keyboard users move between plans with the arrow keys and screen readers announce "Team, radio button, 2 of 3". The summary uses generated content for brevity here; in production, put the plan descriptions in the DOM and show one at a time, because generated text is not dependably announced. The focus rule is the one most often missed: when the interactive element is small and the card is large, move the focus indicator to the card with :has(:focus-visible) so it is actually visible — the reasoning is covered in Creating Accessible Focus Indicators.


Integrating :has() With Container Queries and Layers

:has() works inside every other modern layout feature, and the combinations are where it earns its keep in a design system.

Inside @container blocks. A container query decides that there is room; a :has() rule inside it decides whether there is anything worth using the room for. @container (width > 32rem) { .card:has(> .card__media) { grid-template-columns: 2fr 3fr; } } gives a side-by-side layout only to wide cards that actually have media, while wide text-only cards keep their single column. Neither feature can express that alone.

As a container's own condition. An element can be both a size container and a :has() subject. The container type is unaffected by what matches; only the declarations change. This means a component can switch its container-type on or off by content — for example, only establishing an inline-size container when it holds a nested grid that needs to query it — though in practice leaving containment on is simpler and cheaper to reason about.

Inside cascade layers. Treat content-aware rules as a distinct layer of concerns. A typical order is reset, tokens, base, components, component-states, with :has() rules in component-states. Because layer order beats specificity, a heavy :has() selector in an earlier layer can never unexpectedly override a light class selector in a later one.

With @supports. Test for the capability with @supports selector(:has(*)). The asterisk is deliberate — some engines reject an empty :has() argument even in a support test — and the result is a clean branch for fallbacks that should apply only when :has() is missing.


Performance and Accessibility Notes

Invalidation cost. :has() is paid when its argument's state changes. Narrow anchors and stable arguments are essentially free; broad anchors such as body combined with volatile arguments such as :hover can force wide style recalculation on every pointer move. Keep hover- and focus-driven :has() rules anchored on the nearest component.

Motion. Layout changes triggered by :has() happen instantly unless animated. When they are animated — a card lifting on selection, a panel expanding — gate the motion behind prefers-reduced-motion, as in the example, and prefer transform and opacity over properties that re-run layout. The motion-specific guidance is in Reducing Motion Preferences in CSS.

Semantics stay put. :has() never changes the DOM, focus order or accessibility tree; it changes presentation only. That makes it safe, but it also means it cannot fix semantics. A "disabled-looking" button styled via :has(:invalid) is still enabled for assistive technology.

Colour is not state. If a :has() rule signals state only through colour — a red border for an invalid field group — add a non-colour cue such as text or an icon, per WCAG 1.4.1.


DevTools Debugging Workflow

  1. Confirm the subject. Select the element you expect to be styled. In the Styles pane, a matching :has() rule appears like any other rule. If it is absent, the selector did not match this element.
  2. Force state. Use the :hov toggle in Chrome, Edge and Firefox, or the element state toggles in Safari's Web Inspector, to force :hover, :focus, :focus-visible or :active on the descendant named in the argument, then re-select the anchor to see whether the rule appears.
  3. Check the combinator. If the rule matches when it should not, look for a missing > — a descendant argument can match deeply nested components.
  4. Check specificity. Hover the selector in Chromium's Styles pane to see its specificity. A :has() with an ID or several classes in its argument can outweigh rules you intended to win.
  5. Profile if slow. Record a Performance trace with selector statistics enabled and sort by elapsed time to find expensive :has() rules.

Browser Compatibility

FeatureChrome / EdgeFirefoxSafari
:has()105+121+15.4+
@supports selector()83+69+14.1+
:user-invalid inside :has()119+88+16.5+
:focus-visible inside :has()86+85+15.4+
Style queries (the published-state alternative)111+151+18+

Every current engine supports :has(). The remaining risk is older installed versions, which is why the baseline-plus-enhancement structure in the step-by-step section is still worth keeping.


Common Pitfalls

PitfallCauseResolution
Outer component reacts to an inner one's contentDescendant argument without >Use :has(> x) for direct children
Rule unexpectedly wins the cascade:has() takes its argument's specificityKeep arguments to classes; use :where() to zero weight
Whole selector ignored in some browsersOne unknown pseudo-class in a non-forgiving listWrap the argument in :is()
Hidden items still counted:nth-child counts display: none elementsUse :nth-child(n of :not([hidden]))
Jank on hoverbody:has(... :hover)Anchor on the nearest component instead

FAQ

Is :has() really a parent selector? It is more general. :has() matches an element if the relative selector inside it matches something relative to that element, so it can test descendants, direct children, the next sibling or any later sibling. Selecting a parent by its child is the most common use, not the only one.

What specificity does :has() have? The pseudo-class itself adds nothing; it takes the specificity of the most specific selector in its argument list. .card:has(#promo) therefore carries an ID's weight, which can make it win against rules you expected to override it.

Can I nest :has() inside :has()? No. :has() is not allowed inside another :has() argument, and pseudo-elements are not allowed in its argument either. Chain two :has() pseudo-classes on the same element instead, or restructure the condition around a different anchor.

What happens in a browser without :has() support? A selector containing :has() is invalid there, so the whole rule is dropped. Write the default layout without :has() so it works everywhere, then add :has() rules as enhancements, optionally inside @supports selector(:has(*)).

Should layout depend on :has() or on a container query? Use :has() when the layout depends on what a component contains or which state its controls are in. Use a container query when it depends on how much space the component has. Many components need both, and they compose without conflict.

Related articles

More pages in the same section.