Responsive Components with CSS Container Queries
Responsive components without media queries
Media queries respond to the viewport. Components live in containers: sidebars, modals, grids. @container lets them respond to their actual available space.
The old hack vs the modern fix
View demo.card {
display: grid;
grid-template-columns: 1fr;
}
@media (min-width: 768px) {
.card {
grid-template-columns: auto 1fr;
}
}.wrapper {
container-type: inline-size;
}
.card {
display: grid;
grid-template-columns: 1fr;
}
@container (width > 400px) {
.card {
grid-template-columns: auto 1fr;
}
}<!-- @container marks the parent as a container --><div class="@container"> <!-- @[400px]: fires when container > 400px --> <div class="grid-cols-1 @[400px]:grid-cols-[auto_1fr]"> Card </div></div>Container queries browser support
Live demo
Why the modern way wins
Component-level responsive
Components adapt to their own container. Same card works in a sidebar, modal, or full-width grid.
Truly reusable
No more breakpoint math for every context. The component carries its responsive logic with it.
Precise control
Query the nearest container, not the whole viewport. Each section of the page can behave independently.
- Key Change
- Scope
- Viewport → Container
- Old Approach
- @media
- Viewport-dependent
- Modern Approach
- @container
- Context-aware
How it works
First, mark a parent as a container with container-type: inline-size. This tells the browser to track its width for query purposes.
container-type: inline-size does more than turn on queries. The element becomes a new formatting context, so its children's margins stop collapsing through it, and it sits beside nearby floats instead of flowing around them. Its width also stops depending on its content. A container that sized itself to its content, like a flex item with no set width or an inline-block, can shrink to zero. Give it a width from outside, such as a grid track or width: 100%.
Then use @container (width > 400px) instead of @media. The query now fires based on the container's width, not the viewport. Your card can be 300px wide in a sidebar and 800px wide in a main area, and it'll adapt correctly in both. For fluid typography, container queries pair well with cqi units.
You can even name containers with container-name to target specific ancestors when nesting multiple containers.