Container Queries Inside CSS Nesting: Keeping Responses Next to the Styles They Change

Before native nesting, a component's container queries lived at the top level of the stylesheet, often far below the component's base rules. Reading a card's styles meant scrolling between .card { … }, .card__title { … } and three @container blocks elsewhere in the file, then mentally reassembling which conditions changed which properties. Native CSS nesting lets @container sit inside the rule it modifies, so each element's base style and its responsive variations live together. The narrow problem this page covers is doing that correctly: how the & selector resolves inside a nested query, what happens to specificity, and the one trap — an element querying itself — that nesting makes easier to fall into. It belongs to Container Query Syntax Basics in the Mastering Container Queries & Responsive Layouts guide.

Why nest container queries

Nesting is about locality. A developer changing how a card's title looks at wide sizes wants to see the title's base styles and its wide-size override in the same place. With nesting, the override is literally inside the title's rule.

.card__title {
  font-size: 1.1rem;
  line-height: 1.3;

  @container card (width > 30rem) {
    font-size: 1.4rem;         /* applies to .card__title */
  }
}

That reads as a single statement: "the title is 1.1rem, or 1.4rem when the card is wider than 30rem." The same structure scales to many properties and several bands without the rules drifting apart as the stylesheet grows. It also makes deletion safe: removing the title's rule removes its responsive behaviour with it, instead of leaving an orphaned @container block that targets a selector nothing uses.

Flat versus nested organisation Left, a flat stylesheet lists base rules for card, title and meta at the top and separate container query blocks at the bottom, with lines connecting each element to its distant overrides. Right, nested rules place each container query inside the element it modifies. Where each element's responsive rules live flat .card__title { … } .card__meta { … } @container (> 30rem) { title } @container (> 30rem) { meta } nested .card__title { font-size: 1.1rem; @container (…) { … } } .card__meta { color: …; @container (…) { … } }

The complete implementation

The card below keeps every container response inside the rule for the element it changes. Resize the demo to see the title, meta line and layout respond.

Live demoCard whose container queries are nested in each rule
Drag the frame: above 32rem the card goes side by side, the title grows and the media turns square; under 20rem the author is hidden. Drag the bottom-right corner to resize the frame in either direction.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Nested container queries</title>
<style>
  body { font: 15px/1.5 system-ui, sans-serif; margin: 1rem; }

  /* The wrapper is the container, never the element being styled. */
  .card-slot {
    container: card / inline-size;
  }

  .card {
    display: grid;
    gap: 0.75rem;
    padding: 1rem;
    border: 1px solid #cbd5e1;
    border-radius: 12px;

    /* Declarations directly inside apply to .card itself: the query
       looks UP from .card and finds .card-slot. */
    @container card (width > 32rem) {
      grid-template-columns: 10rem 1fr;
      padding: 1.5rem;
    }
  }

  .card__media {
    aspect-ratio: 16 / 9;
    border-radius: 8px;
    background: linear-gradient(135deg, #c7d2fe, #818cf8);

    @container card (width > 32rem) {
      aspect-ratio: 1;
    }
  }

  .card__title {
    margin: 0;
    font-size: 1.1rem;

    @container card (width > 32rem) {
      font-size: 1.35rem;
    }
  }

  .card__meta {
    margin: 0;
    color: #475569;
    font-size: 0.85rem;

    /* Nest selectors too: & is .card__meta. */
    & time { font-variant-numeric: tabular-nums; }

    @container card (width < 20rem) {
      /* Hide the secondary meta on very narrow cards. */
      & .card__author { display: none; }
    }
  }
</style>
</head>
<body>
  <div class="card-slot">
    <article class="card">
      <div class="card__media" role="img" aria-label="Abstract illustration"></div>
      <div>
        <h3 class="card__title">Designing for containers</h3>
        <p class="card__meta"><span class="card__author">Mira Chen</span> · <time>12 Sep</time></p>
      </div>
    </article>
  </div>
</body>
</html>

Each nested @container block without a selector applies its declarations to the enclosing rule's element. Where the change targets a descendant, & .card__author inside the query reaches it. The resulting CSS is exactly what the flat version would produce; nesting changes only how it is written.

The key technique: how & and bare declarations resolve

Two forms appear inside a nested conditional rule, and they resolve differently.

What a nested @container expands to Left: .card__meta containing @container with a bare declaration expands to @container { .card__meta { declaration } }. Right: .card__meta containing @container with & .card__author expands to @container { .card__meta .card__author { declaration } }. Nested source and its flat equivalent .x { @container (…) { color: red; } } .x { @container (…) { & .y { color: red; } } } expands to expands to @container (…) { .x { color: red } } @container (…) { .x .y { color: red } }

The container lookup always starts from the element the final selector matches. For bare declarations that is the enclosing element; for & .y it is .y. Both look upward for a container, which is where the classic trap reappears: if .card is itself the container and you nest a bare-declaration @container inside .card, the query looks for a container above .card, finds none (or the wrong one), and never matches. Nesting makes this easy to write by accident, because the container declaration and the query sit a few lines apart in the same rule. Keep the container on a wrapper, as the example does with .card-slot, and the problem cannot arise.

Specificity follows the nesting rules: a nested selector behaves as if & were :is(<parent selectors>). For a single class parent the result is identical to the flat equivalent. If the parent is a list such as .card, #featured, every nested rule inherits the ID's weight, which is a good reason to keep component parents to a single class.

Migrating a flat stylesheet to nested queries

Converting an existing component from top-level @container blocks to nested ones is mechanical, and because the output is equivalent, it can be verified precisely.

Take one @container block at a time. For each rule inside it, find the matching base rule for the same selector and move the declarations into a nested @container with the same condition inside that base rule. Where a block contains rules for several elements, it splits into several nested queries — one per element — each repeating the condition. That repetition is the price of locality, and it is usually worth paying; where it is not, the token approach below removes it.

Check the order carefully. In a flat stylesheet, a later top-level @container block overrides an earlier one when both match. After nesting, the relative order of nested queries within a rule decides precedence instead. If two bands overlapped in the flat version and relied on source order to resolve, nesting can reverse the winner. Converting the conditions to non-overlapping range syntax first removes the ambiguity entirely.

Finally, compare computed styles. Chromium's Computed pane and Firefox's rules view both show which rule supplied each value; checking a handful of elements at each band before and after the migration confirms nothing changed. A visual regression test at three container widths does the same automatically.

Organising nested queries in a component file

Nesting invites deep indentation. A few conventions keep nested component files readable:

  • One level of element nesting. Nest element states and descendants of a component one level deep; avoid chains of nested selectors that mirror the DOM, which recreate the specificity problems methodologies such as BEM exist to prevent.
  • Queries last inside each rule. Base declarations first, nested selectors next, conditional rules last. The eye reads the default before the variations.
  • Named containers. Always name the container in component queries (@container card …) so nested rules cannot silently bind to an unrelated ancestor container when the component is embedded elsewhere.
  • Shared bands as tokens. If several elements change at the same band, consider setting custom properties in one nested query on the component root and reading them in descendants, rather than repeating the same @container condition in every element's rule. The token approach is shown in Container Query Range Syntax and Logic.

The same nesting works for @media, @supports and @starting-style, so an element's entry animation can live inside its rule as well. That makes nesting particularly effective for components with both layout and motion variants — see Container Query Hover Affordances for motion that changes with container size.

Variation: nesting inside cascade layers

Component files often sit inside a cascade layer. Nesting and layers compose naturally: the layer wraps the component, the component wraps its element rules, and each element rule wraps its queries.

@layer components {
  .card-slot { container: card / inline-size; }

  .card {
    display: grid;
    gap: 0.75rem;

    @container card (width > 32rem) {
      grid-template-columns: 10rem 1fr;
    }

    &:focus-within {
      outline: 2px solid #4f46e5;
      outline-offset: 3px;
    }

    @media (prefers-reduced-motion: no-preference) {
      transition: box-shadow 150ms ease;
      &:hover { box-shadow: 0 8px 24px rgb(15 23 42 / 0.12); }
    }
  }
}

Layer order still decides precedence between layers, so a nested container query in components cannot override a rule in a later utilities layer, regardless of how specific it is. That combination — nesting for locality, layers for precedence — is the structure recommended in Cascade Layers for Reset and Tokens.

Browser support

Native CSS nesting, including nested conditional group rules such as @container and @media, is supported in current versions of Chrome, Edge, Firefox and Safari. Container queries require Chrome and Edge 105+, Firefox 110+ or Safari 16+, and cascade layers Chrome and Edge 99+, Firefox 97+ or Safari 15.4+. For older browsers, a build step can flatten nested CSS into the equivalent top-level rules; the output is identical in behaviour.

FAQ

Can @container be nested inside a CSS rule? Yes. With native CSS nesting, conditional group rules such as @container, @media and @supports can be placed inside a style rule. Declarations directly inside the nested @container apply to the parent selector, as if written with &.

What does & mean inside a nested container query? It refers to the selector of the enclosing style rule. In .card { @container (width > 30rem) { & .title { … } } }, the & stands for .card, so the rule targets .card .title when the container condition matches.

Does nesting change specificity? The nested selector's specificity is calculated as if & were replaced by :is() around the parent selector list. For a single simple parent like .card, the result matches the unnested equivalent. For a parent list mixing an ID and classes, every nested rule inherits the highest specificity in the list.

Can the element being nested into be its own container? It can establish a container, but a container query never matches against the element itself. Declarations placed directly inside a nested @container in the container's own rule look for a container above it. Put the container on a wrapper, or target descendants with & inside the query.

Related articles

More pages in the same section.