Container-Aware Responsive Card Grid
Build a card grid that adapts column count and card layout to its host container width using stacked @container rules — independent of viewport breakpoints.
Detailed Explanation
Two Levels of Adaptation in One Component
A truly portable card grid needs to react on two levels:
- Grid level — how many columns?
- Card level — how does each card lay out internally?
Container queries let you handle both, with the grid host as the outer container and each card host as a nested container.
The CSS
.cards-host {
container-type: inline-size;
container-name: cards;
}
.cards-grid {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
}
@container cards (min-width: 480px) {
.cards-grid { grid-template-columns: repeat(2, 1fr); }
}
@container cards (min-width: 900px) {
.cards-grid { grid-template-columns: repeat(3, 1fr); }
}
/* Each card is also a container */
.card-host {
container-type: inline-size;
container-name: card;
}
@container card (min-width: 280px) {
.card-image { aspect-ratio: 16 / 9; }
.card-title { font-size: 1.05rem; }
}
Why Nest the Containers?
When the outer grid switches from one column (cards ~600px wide) to three columns (cards ~280px wide), each card needs to react. With nested containment, the card's own rules fire automatically based on the card's actual width — no JS, no resize observer.
Avoid Style Recursion
Avoid putting both the outer grid and the inner card containers under the same name. Use distinct names (cards, card) so a rule meant for the grid can never accidentally match a card.
Real-World Tuning
- 480px first breakpoint: cards stay readable down to ~230px each
- 900px second breakpoint: gives ~280px cards in three columns
- 1200px optional third breakpoint: jump to four columns if your cards work that small
This pattern powers product listings, blog summaries, course catalogs, and any UI where the grid must work everywhere from a 320px sidebar to a 1600px landing page section.
Use Case
Use this nested container pattern for marketing card grids, product listings, course catalogs, and any reusable grid component shipped in design systems where the same grid must work in any layout context.