CSS Container Queries: Component-Level Responsive Design
Media queries respond to the viewport; container queries respond to a parent element. Learn @container syntax, size containment, and how to build truly reusable responsive components without viewport hacks.
Viewport Queries Break Component Reuse
A card component that looks perfect at 768px viewport width may be crushed inside a 300px sidebar or stretched in a dashboard grid. Media queries only know about the browser window. They cannot adapt to the space a component actually occupies. Container queries fix this by enabling styles based on the dimensions of a containing element.
Setting Up a Query Container
Mark an ancestor as a container with container-type (usually inline-size for width-based breakpoints):
.card-wrapper {
container-type: inline-size;
container-name: card;
}
@container card (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 120px 1fr;
gap: 1rem;
}
}
@container card (max-width: 399px) {
.card {
flex-direction: column;
}
}
Container Query Units
Use cqw, cqh, cqi, and cqmin/cqmax for sizes relative to the container, ideal for fluid typography and spacing that scales with component width, not viewport width.
@container (min-width: 500px) {
.headline {
font-size: clamp(1.25rem, 4cqi, 2rem);
}
}
Style Queries (Emerging)
Container style queries (@container style()) respond to custom properties set on the container, enabling theme variants (compact vs. comfortable density) without prop-drilling classes through React or Vue layers.
Performance and Containment
Container queries require layout containment on the query container, which can isolate reflow, a net win for complex pages. Test in design systems: one ProductCard should work in carousels, modals, and full-width grids without duplicate breakpoint logic.
Browser Support and Fallbacks
Container queries are supported in all modern browsers. For legacy environments, progressive enhancement with simple stacked layouts remains acceptable; the component-enhanced layout activates where supported.
Container queries mark a shift from page-centric to component-centric responsive design: the missing primitive for design systems and micro-frontends alike.