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
container-type: inline-sizeenables inline-axis size containment: the container's width no longer depends on its children.- This containment breaks the circular sizing dependency that historically blocked parent queries (and forced teams into the JS ResizeObserver Pattern).
- During the Layout pass of the Browser Rendering Pipeline, the engine resolves container size, evaluates
@containerrules, 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+ (
@containerBaseline): Native resolution inside the CSS engine without JS or hydration mismatch.
Production Pitfalls
Production Pitfall
- Container collapsing to 0 px: Applying
container-type: inline-sizeon aninlineelement or flex/grid item without intrinsic width collapses it to0px. - Missing
container-name: Without a name,@containertargets 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@mediaqueries.
Connections & Logical Next Steps
Useful Prerequisites
Foundational node
CSS Container Queries (@container)
Under the HoodBaseline · Widely
Browser Rendering Pipeline (Critical Rendering Path)
Rendering Pipeline
Requires contain: inline-size (layout containment) to break parent-child circular dependencies.
Often Confused WithSuperseded
JS ResizeObserver Pattern for Adaptive Layout
CSS & Layout
ResizeObserver mutates styles in JS after Layout, whereas @container queries resolve size rules in one CSS pass.
ReplacesSuperseded
JS ResizeObserver Pattern for Adaptive Layout
CSS & Layout
Eliminates ResizeObserver + JS class toggling to adapt components to their container.