Nested Containers — Outer Layout, Inner Components
Nest CSS container queries by combining a layout-level container with component-level containers using container-name to give each level its own breakpoints independently.
Detailed Explanation
Two Levels of Containment Working Together
Nested containers let you build layouts where the page region has its own responsive rules and the components inside it have separate, independent rules. This is the bread and butter of design systems.
Architecture
/* Outer: a page region */
.region-host {
container-type: inline-size;
container-name: region;
}
/* Inner: a card component */
.card-host {
container-type: inline-size;
container-name: card;
}
/* Region-level rules */
@container region (min-width: 1024px) {
.region-grid {
grid-template-columns: 1fr 1fr 1fr;
}
}
/* Card-level rules */
@container card (min-width: 320px) {
.card {
display: grid;
grid-template-columns: 80px 1fr;
}
}
Why Naming Matters Here
If you used unnamed containers, an inner card would resolve queries against itself, never the outer region. By naming each level, you can target either one explicitly.
Resolution Order Without Names
/* Without container-name */
@container (min-width: 1024px) {
/* Always matches the NEAREST container with containment */
/* Inside .card-host, that's the card — never the region! */
}
This silent resolution is the #1 source of "my container query doesn't work" bug reports.
Real-World Example: Dashboard Page
.dashboard-host { container: dashboard / inline-size; }
.widget-host { container: widget / inline-size; }
/* Page-level: switch from single-column to sidebar+main */
@container dashboard (min-width: 1280px) {
.dashboard {
display: grid;
grid-template-columns: 240px 1fr;
}
}
/* Widget-level: switch each widget independently */
@container widget (min-width: 360px) {
.widget-chart { display: block; }
}
When the user collapses the sidebar (changing the dashboard width), each widget's own width changes too. Both queries fire independently — page layout shifts AND each widget reflows internally.
Cardinality Rule of Thumb
Don't nest more than 2-3 levels deep. Beyond that, debugging which query matched what becomes painful. If you find yourself wanting 4+ levels, consider whether the inner components really need their own containment.
Use Case
Use nested containers in dashboards, page builders, CMS-driven layouts, and design-system layouts where page regions and individual components both need independent responsive behavior.