Skip to content
FEE
Frontend Engineering Essentials
Senior Level

[FEE-11002] Container Queries — Size & Style ​

INFO

Make any component truly responsive by querying the space it actually occupies — not the viewport — and by querying custom properties on ancestor elements to drive declarative theming without JavaScript.

Baseline Newly Available

Size queries supported in Chrome 105+, Firefox 110+, Safari 16+. Style queries supported in Chrome 111+, Firefox 127+, Safari 18+. Use progressive enhancement for older browsers.

Context ​

Media queries were the first CSS mechanism for responsive design, but they answer the wrong question for components. A media query asks "how wide is the viewport?" — yet a card component inside a 300 px sidebar and the same card component spanning an 800 px main content area both live in the same viewport. The viewport width is identical; the available space for the component is not.

The industry compensated with workarounds:

  1. JavaScript ResizeObserver — attach an observer to the component, compute a size class in JS, write a data attribute or class to the DOM, then target that class in CSS. Works, but adds layout thrashing, costs runtime, and requires hydration before styles are correct in SSR environments.
  2. CSS Grid auto-fit / auto-fill — lets columns collapse when space is tight, but does not allow component-internal layout changes such as switching from horizontal to vertical image placement.
  3. Passing size props from parent — in component-based frameworks, pass an explicit size="compact" prop. Works, but leaks layout knowledge up the tree and couples parent to child implementation details.

Container Queries move this decision into CSS. The component declares that it participates in containment; the browser tracks its size as part of layout; the component's own style rules respond to that size — with no JavaScript, no observers, and no class toggling.

Style queries extend this idea: instead of querying a number (size), they query a value (a custom property). A parent sets --variant: featured on a wrapper; children query @container style(--variant: featured) to apply variant styles. This brings prop-driven styling into pure CSS.

Scenario ​

You are building a design-system card component that is used in three contexts:

  • A narrow sidebar (approx. 280 px available)
  • A two-column article grid (approx. 420 px available)
  • A full-width hero section (approx. 900 px available)

In the sidebar the card must stack vertically (thumbnail on top, text below). In the article grid and hero section it should switch to horizontal layout. In the hero section it should also increase font sizes and show a "featured" badge.

With media queries you cannot express this — the viewport is the same regardless of which slot the card occupies. With Container Queries you wrap each slot in a containment context and let the card respond to its actual available width and to a --variant custom property set on the hero wrapper.

Best Practices ​

  • MUST name containers with container-name when multiple nested containers exist. An unnamed @container rule matches the nearest ancestor with a containment context — in deeply nested layouts this silently resolves to the wrong container.
  • SHOULD use container-type: inline-size for the majority of component layouts. It tracks only the inline (horizontal) dimension, which is what most layout switches need, and is cheaper than container-type: size.
  • MUST NOT apply container-type to elements that rely on their content to determine their block (vertical) height. Both inline-size and size apply layout containment in the block direction, which severs the element's height from its content — causing it to collapse to zero if no explicit height is set.
  • SHOULD use the container shorthand (container: card / inline-size) to declare both name and type in one declaration.
  • SHOULD use style queries for theming variants (--variant: compact, --theme: dark) rather than toggling CSS classes from JavaScript. The parent sets one custom property; all children that care can query it independently.
  • MUST apply progressive enhancement. Wrap @container rules inside a @supports (container-type: inline-size) block so older browsers receive the default (typically stacked) layout rather than a broken one.
  • SHOULD NOT name a container the same as a custom property used in a style query on that container — the two namespaces are unrelated, but identical names create confusing code.

Design Thinking ​

Why media queries fail components ​

A media query reports viewport geometry. A component embedded in a layout does not control — and often cannot predict — how much of the viewport it will occupy. The same .card markup can render at 280 px in a sidebar and 840 px as a hero; both cases share a viewport of, say, 1280 px. A media query at min-width: 600px fires for both, yet the sidebar card has no room to lay out horizontally.

The underlying mismatch: media queries answer a page-level question for a component-level problem.

How JavaScript filled the gap ​

The ResizeObserver API (2020, widely available) let developers observe an element's own size and react to it. The typical pattern:

  1. Observe .card for size changes.
  2. In the callback, read contentRect.width.
  3. Toggle a class (card--horizontal) on the element.
  4. CSS targets .card--horizontal to apply the layout.

This works, but it is brittle in several ways: the observer fires after layout (causing a second layout pass), it must be set up in JavaScript before it has any effect (breaking server-rendered HTML), and every component instance requires its own observer. In a list of 50 cards, that is 50 active observers.

Container Queries as the CSS answer ​

container-type tells the browser that this element's descendant styles may depend on the element's size. The browser then tracks that element's size as a first-class layout primitive — the same way it tracks viewport size for media queries. @container rules are evaluated during the same layout pass as everything else, before paint. No second pass, no observer callbacks, no class toggling.

Style queries extend the same model to custom properties. A parent declares a custom property; the browser makes that value queryable on the container. Children opt in by writing @container style(--prop: value). This is the CSS equivalent of passing a prop down the tree — except no JavaScript framework is needed, and any descendant at any depth can query the value independently.

The key conceptual shift: the component declares its own responsiveness. It does not depend on the parent knowing about its internals or on JavaScript wiring up size classes. The component is self-contained and portable.

Example ​

Example 1 — Size query: horizontal / vertical card layout ​

A .card component that switches from vertical (default, image on top) to horizontal (image left, content right) when its container reaches 400 px.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Container Query — Card</title>
  <style>
    /* ── Layout ──────────────────────────────────────────── */
    .layout {
      display: grid;
      grid-template-columns: 280px 1fr;
      gap: 24px;
      padding: 24px;
      font-family: system-ui, sans-serif;
    }

    /* ── Containment contexts ────────────────────────────── */
    .sidebar,
    .main {
      container-type: inline-size;
    }

    .sidebar { background: #f5f5f5; padding: 16px; }
    .main    { background: #fafafa; padding: 16px; }

    /* ── Card — default (vertical / narrow) ─────────────── */
    .card {
      border: 1px solid #ddd;
      border-radius: 8px;
      overflow: hidden;
      background: #fff;
    }

    .card__image {
      width: 100%;
      aspect-ratio: 16 / 9;
      object-fit: cover;
      display: block;
      background: #c9d6e3; /* placeholder colour */
    }

    .card__body {
      padding: 12px;
    }

    .card__title {
      margin: 0 0 8px;
      font-size: 1rem;
    }

    .card__desc {
      margin: 0;
      font-size: 0.875rem;
      color: #555;
    }

    /* ── Card — horizontal layout when container >= 400 px ─ */
    @container (min-width: 400px) {
      .card {
        display: grid;
        grid-template-columns: 160px 1fr;
      }

      .card__image {
        aspect-ratio: unset;
        height: 100%;
      }
    }
  </style>
</head>
<body>
  <div class="layout">

    <!-- Narrow container: card stays vertical -->
    <aside class="sidebar">
      <article class="card">
        <div class="card__image" role="img" aria-label="Placeholder"></div>
        <div class="card__body">
          <h2 class="card__title">Sidebar Card</h2>
          <p class="card__desc">This container is 280 px wide — card stays vertical.</p>
        </div>
      </article>
    </aside>

    <!-- Wide container: card switches to horizontal -->
    <main class="main">
      <article class="card">
        <div class="card__image" role="img" aria-label="Placeholder"></div>
        <div class="card__body">
          <h2 class="card__title">Main Content Card</h2>
          <p class="card__desc">This container is wider than 400 px — card goes horizontal.</p>
        </div>
      </article>
    </main>

  </div>
</body>
</html>

The .sidebar and .main wrappers both declare container-type: inline-size. The .card itself contains no knowledge of the page layout — it simply responds to whatever space it is given.

Example 2 — Style query: theme variant without JavaScript ​

A --theme: dark custom property on a wrapper drives card colours declaratively. No class toggling, no JS.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Style Query — Theme Variant</title>
  <style>
    body {
      font-family: system-ui, sans-serif;
      padding: 24px;
      display: flex;
      gap: 24px;
    }

    /* ── Wrappers set the variant via a custom property ─── */
    /* No container-type needed for style queries */
    .wrapper-light { --theme: light; }
    .wrapper-dark  { --theme: dark;  background: #1a1a2e; padding: 16px; border-radius: 8px; }

    /* ── Card defaults (light theme) ─────────────────────── */
    .card {
      border: 1px solid #ddd;
      border-radius: 8px;
      padding: 16px;
      background: #ffffff;
      color: #111;
      width: 220px;
    }

    .card__title {
      margin: 0 0 8px;
      font-size: 1rem;
    }

    .card__desc {
      margin: 0;
      font-size: 0.875rem;
      color: #555;
    }

    /* ── Dark variant via style query ─────────────────────── */
    @container style(--theme: dark) {
      .card {
        background: #16213e;
        border-color: #0f3460;
        color: #e0e0e0;
      }

      .card__desc {
        color: #9e9e9e;
      }
    }
  </style>
</head>
<body>

  <div class="wrapper-light">
    <article class="card">
      <h2 class="card__title">Light Card</h2>
      <p class="card__desc">Rendered inside .wrapper-light — default colours apply.</p>
    </article>
  </div>

  <div class="wrapper-dark">
    <article class="card">
      <h2 class="card__title">Dark Card</h2>
      <p class="card__desc">Rendered inside .wrapper-dark — style query applies dark colours.</p>
    </article>
  </div>

</body>
</html>

Notice that .wrapper-dark does not declare container-type. Style queries work on any element with a custom property — no containment context is required.

Deep Dive ​

Container query units ​

Container queries introduce a set of viewport-relative-style units that resolve against the queried container rather than the viewport:

UnitResolves to
cqw1% of the container's inline size
cqh1% of the container's block size
cqi1% of the container's inline size (alias)
cqb1% of the container's block size (alias)
cqminSmaller of cqi and cqb
cqmaxLarger of cqi and cqb

Use these for typography and spacing that should scale with the component's available space:

css
.card__title {
  /* Font size scales between 14px and 22px as container grows */
  font-size: clamp(0.875rem, 4cqi, 1.375rem);
}

Nesting containers ​

When a container is placed inside another container, it becomes its own containment context for its descendants:

css
.page-layout {
  container: page / inline-size;
}

.sidebar {
  container: sidebar / inline-size;
}

.widget {
  /* This @container resolves against .sidebar, not .page-layout */
  /* because .sidebar is the nearest ancestor with containment */
}

An unnamed @container rule always resolves against the nearest ancestor that has any container-type set. Naming containers precisely avoids accidental resolution against the wrong ancestor.

Style query current limitations ​

As of 2026, style queries can only query custom properties (CSS variables). They cannot query computed values:

css
/* VALID — custom property query */
@container style(--variant: featured) { ... }

/* NOT VALID — computed value query (not yet in any browser) */
@container style(color: red) { ... }
@container style(width: 300px) { ... }

The CSS Working Group has discussed extending style queries to computed values, but browser implementations have not shipped this. Write code today that only queries custom properties.

Performance: layout containment implications ​

container-type: inline-size applies layout containment in the block direction. This has two notable side effects:

  1. Block height is severed from content — the container's block size is determined by its own sizing context, not its contents. If no height is specified, it collapses. This is by design: it lets the browser skip layout of the container's subtree when only the container's inline size changes.
  2. Stacking context — layout containment creates a new stacking context (like position: relative with a z-index). This can affect z-index behaviour for absolutely positioned children inside the container.

container-type: size applies containment in both dimensions and is more expensive. Use it only when your @container rules query the block dimension (e.g., min-height).

The container shorthand ​

css
/* Longhand */
.card-wrapper {
  container-type: inline-size;
  container-name: card;
}

/* Equivalent shorthand */
.card-wrapper {
  container: card / inline-size;
}

The shorthand is container: <name> / <type>. The slash separator is required. To declare a type without a name, write container: none / inline-size.

Browser Support ​

BrowserFirst versionNotes
Chrome105Size queries
Firefox110Size queries
Safari16Size queries
Edge105Chromium-based

Style queries (@container style()) shipped later:

BrowserFirst versionNotes
Chrome111Custom property style queries
Firefox127Custom property style queries
Safari18Custom property style queries

Progressive enhancement pattern:

css
/* Styles here apply to all browsers */
.card {
  /* Default (narrow / vertical) layout */
}

@supports (container-type: inline-size) {
  .card-wrapper {
    container-type: inline-size;
  }

  @container (min-width: 400px) {
    .card {
      /* Horizontal layout */
    }
  }
}

Feature detection in JavaScript:

js
const supportsContainerQueries =
  CSS.supports('container-type', 'inline-size');

Internal References ​

  • FEE-11001 CSS Anchor Positioning — Both anchor positioning and container queries use containment concepts: anchor positioning scopes name resolution to subtrees via anchor-scope, while container queries scope style evaluation to a container subtree.
  • FEE-11201 @property — Style queries query custom properties; @property lets you declare a custom property's syntax, initial value, and inheritance. A typed custom property queried in a style query is more predictable because its value is always of the declared type, never an empty string from an unset variable.

References ​