Nested Container Queries — Containers Inside Containers
Learn how to use nested CSS container queries with named containers to create independently responsive components within responsive layouts.
Detailed Explanation
Nested Container Queries
Real-world UIs often have containers inside containers: a sidebar inside a dashboard, a card inside a grid inside a page. Named containers make nested queries predictable and maintainable.
The Pattern
.dashboard {
container: dashboard / inline-size;
}
.panel {
container: panel / inline-size;
}
/* Dashboard-level layout changes */
@container dashboard (min-width: 1024px) {
.dashboard-layout {
display: grid;
grid-template-columns: 300px 1fr;
}
}
/* Panel-level component changes */
@container panel (min-width: 400px) {
.panel-content {
display: grid;
grid-template-columns: 1fr 1fr;
}
}
How Resolution Works
When a child element has a @container query:
- The browser walks up the DOM tree looking for an ancestor with the matching
container-name. - If unnamed, it matches the nearest ancestor with any containment.
- If named, it skips ancestors without that name.
Independence
The panel component does not care about the dashboard's width. It responds only to its own container's width. If the dashboard is 1200px wide and the panel occupies 400px, the panel's query fires at its 400px threshold, not 1200px.
Common Mistake
/* Without names, both match the nearest ancestor */
@container (min-width: 400px) { /* This always matches .panel */ }
@container (min-width: 1024px) { /* This also matches .panel, not .dashboard! */ }
Always use container-name when nesting containers to avoid ambiguity.
Use Case
Use this pattern in complex layouts like dashboards, CMS page builders, or any UI where responsive components are nested inside other responsive containers. Named containers ensure each level responds independently.