CSS Subgrid
subgrid lets a nested grid adopt its parent's column or row tracks instead of inventing isolated ones. Child items inside sibling cards then participate in the same CSS Grid Track Sizing pass, keeping headings, media, and footers aligned across rows.
Independent Nested Grids vs subgrid
Compare misaligned sibling card internals against shared parent row tracks.
.cards { display: grid; grid-template-columns: repeat(3, 1fr); }
.card {
display: grid;
grid-template-rows: auto 1fr auto;
/* Titles & footers misalign across cards */
}A 2-line title in Card 1 misaligns Card 2’s body and footer.
.cards { display: grid; grid-template-columns: repeat(3, 1fr); }
.card {
display: grid;
grid-row: span 3;
grid-template-rows: subgrid;
}All card titles, bodies, and footers share the exact same row tracks.
Under the Hood
Without subgrid, each card is an island measuring its own ceiling height; with subgrid, every card bolts its shelves onto the same wall studs.
- Track Adoption: Setting
grid-template-rows: subgridmaps the child's row lines onto the parent's spanned tracks. - Upward Sizing: Intrinsic content inside the subgrid feeds back into the parent's Render Tree & Layout track-sizing pass, expanding the shared row for all siblings.
- Explicit Span: The subgrid container must span enough parent tracks (
grid-row: span 3) to hold its internal rows, otherwise extra children pile into the last track.
.pricing-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1.5rem;
}
.pricing-card {
display: grid;
grid-row: span 3;
grid-template-rows: subgrid;
row-gap: 0.75rem; /* Overrides parent row-gap locally */
}Problem Genealogy
- 2017–2022:
display: contentswas abused to flatten card wrappers into a parent grid, breaking background, border, and accessibility semantics on the card container. - 2023+: CSS Grid Level 2 (
subgrid) shipped in all major engines, preserving the card wrapper box while sharing tracks.
Production Pitfalls
- Forgetting
grid-row: span N: A card defaults to spanning 1 row; withoutspan N, all 3 subgrid children collide inside that single row. - Inherited
gap: Subgrids inherit the parent'sgapautomatically; overriderow-gaporcolumn-gapon the subgrid if internal spacing should be tighter.
- When not to use
subgrid: Avoidsubgridwhen cards have variable numbers of internal sections, use Flexboxmargin-top: autoon the footer instead.
Connections & Logical Next Steps
Subgrid participates directly in the parent grid’s track-sizing algorithm.
Synchronizes nested subgrid item geometry with parent grid tracks during layout calculation.
Independent nested grids size their own tracks, whereas subgrid inherits track definitions from the parent grid.