CSS & LayoutBaseline · Widely

CSS Container Queries (@container)

Mental Model

@container applies CSS rules based on the width or height of an ancestor declared with container-type: inline-size. Components adapt to their actual insertion slot (sidebar, grid, modal) with zero JavaScript.

Interactive Simulator

Component Adaptation: @container vs @media

Shrink the parent container width to observe grid column behavior.

@container (inline-size)360px → 2 cols
Card 1
Card 2
Card 3
Container Width
360 px
Grid Columns
2 col.
Reference Query
@container (inline-size)
Component adapts to its container (360px for 2 column(s)), independent of the viewport.
Card 1
Card 2
Card 3

Under the Hood

  1. container-type: inline-size enables inline-axis size containment: the container's width no longer depends on its children.
  2. This containment breaks the circular sizing dependency that historically blocked parent queries (and forced teams into the JS ResizeObserver Pattern).
  3. During the Layout pass of the Browser Rendering Pipeline, the engine resolves container size, evaluates @container rules, and resolves descendant styles and geometry in a single top-down pass.
CSS
.card-slot {
  container-type: inline-size;
  container-name: card;
}

@container card (min-width: 420px) {
  .card {
    display: grid;
    grid-template-columns: 160px 1fr;
    gap: 1rem;
  }
}

Problem Genealogy

  • 2010 (@media): Viewport-only adaptation, unusable for reusable components dropped into sidebars or drawers.
  • 2018 (ResizeObserver + React state): Post-paint JS measurement causing double renders, hydration flash, and 150 lines of hook plumbing for a two-column card.
  • 2023+ (@container Baseline): Native resolution inside the CSS engine without JS or hydration mismatch.

Production Pitfalls

Production Pitfall
  • Container collapsing to 0 px: Applying container-type: inline-size on an inline element or flex/grid item without intrinsic width collapses it to 0px.
  • Missing container-name: Without a name, @container targets the nearest ancestor container, which can misfire in nested layouts.
When Not to Use
  • When not to use @container: For macro page layout (global navigation, main page grid), keep viewport @media queries.

Connections & Logical Next Steps

Useful Prerequisites
Foundational node
CSS & LayoutCSS Container Queries (@container)

Mechanical Comparisons