CSS Subgrid: Aligning Nested Grid Items Across Tracks
Learn CSS subgrid — the feature that solves nested grid alignment. Understand how child elements can participate in their grandparent's grid, enabling card layouts with perfectly aligned content.
Key Takeaways
- When you place cards in a CSS Grid, each card is a grid item.
- grid-template-columns: repeat(3, 1fr);
- Product cards**: Price, title, and 'Add to Cart' aligned across cards
- Subgrid is supported in all modern browsers (Chrome 117+, Firefox 71+, Safari 16+).
CSS Grid Generator
The Nested Grid Problem
When you place cards in a CSS Grid, each card is a grid item. But the content inside each card — title, description, footer — creates a separate formatting context. Titles of different lengths cause descriptions and footers to misalign across cards. Subgrid solves this by letting inner elements participate in the outer grid's row tracks.
How Subgrid Works
.card-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: subgrid; /* Not here — on children */
gap: 1.5rem;
}
.card {
display: grid;
grid-row: span 3; /* Card spans 3 parent rows */
grid-template-rows: subgrid; /* Inherit parent's row tracks */
}
Each card's title, content, and footer now snap to the same row tracks, creating perfect horizontal alignment across the grid.
Before and After Subgrid
| Without Subgrid | With Subgrid |
|---|---|
| Card heights vary | Cards share row tracks |
| Footers misalign | Footers align horizontally |
| Requires fixed heights | Content drives sizing |
| JavaScript alignment hacks | Pure CSS solution |
Common Use Cases
- Product cards: Price, title, and 'Add to Cart' aligned across cards
- Feature comparisons: Rows align across columns
- Form layouts: Labels and inputs align in nested fieldsets
- Navigation menus: Submenu items align with parent grid
Browser Support
Subgrid is supported in all modern browsers (Chrome 117+, Firefox 71+, Safari 16+). For older browsers, the inner grid falls back to independent sizing, which is functional but not perfectly aligned.
Experiment with subgrid layouts using the Peasy CSS grid builder.