Container Query
A CSS capability allowing components to adapt their internal layout based on their parent container's size rather than the global viewport
Table of Contents
Structure Diagram
Viewport-based · Macro page layout
- MeasuresEntire browser viewport
- Reuse LimitCannot tell sidebar vs main slot on desktop
- Best ForPage shells, global navigation shifts
Parent box-based · Modular components
- MeasuresNearest container-type ancestor width
- Reuse BenefitAuto-switches stacked in sidebar, horizontal in main
- Best ForDesign system cards, widgets, panels
What is Container Query?
A CSS capability allowing components to adapt their internal layout based on their parent container's size rather than the global viewport. It is a core concept in Layout & Responsive within UI / UX.
Core Principles
CSS Container Queries allow a component to respond to the dimensions of its nearest designated parent container (container-type: inline-size) via @container (min-width: 420px), rather than relying solely on the global browser viewport.
Previously, placing the same card in both a wide main column and a narrow desktop sidebar required manual props like compact={true}. Container queries make components genuinely portable and self-adapting.
Practical Takeaways
- Combine
@mediafor shells with@containerfor components: Let media queries orchestrate top-level page structure while container queries handle cards, widgets, and embedded modules. - Name nested containers explicitly: Use
container-name: cardand@container card (min-width: 360px)so deeply nested layouts always query the intended wrapper. - Leverage container query units (
cqi,cqw): Fluidly scale card titles or spacing withclamp(1rem, 4cqi, 1.5rem)relative to the component's own width.
Notable Examples
- Context-aware cards: Rendering horizontally inside a wide main feed and stacking vertically inside a narrow sidebar without extra props.
- Resizable dashboard panels: Reflowing KPI metrics and chart legends smoothly as users drag split-pane dividers.
- Portable design system primitives: Reusable modules that adapt reliably regardless of which host layout embeds them.