patterncssTip
CSS Subgrid for aligning nested elements to parent grid tracks
Viewed 0 times
subgridgridnested gridalignmentcard layouttrack
Problem
In a grid of cards, content inside each card (like titles and descriptions) cannot align across cards without JavaScript measurement, because each card is its own formatting context.
Solution
Use subgrid to make a grid item's children participate in the parent grid's tracks:
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto auto auto; /* shared row tracks */
gap: 1rem;
}
.card {
display: grid;
grid-row: span 3; /* occupy 3 rows */
grid-template-rows: subgrid; /* inherit parent row tracks */
}
/* Now .card's children align to the parent grid's rows */
.card__image { grid-row: 1; }
.card__title { grid-row: 2; }
.card__body { grid-row: 3; }Why
Without subgrid, each grid item is an independent layout context — its children cannot align with children in sibling items. Subgrid bridges this gap by propagating the parent's track definitions into the child grid.
Gotchas
- Subgrid is supported in all modern browsers as of 2023 (Chrome 117+, Firefox 71+, Safari 16+).
- Subgrid can be applied to rows, columns, or both independently.
- Gap on the parent grid is inherited by the subgrid — the subgrid does not define its own gap unless explicitly set.
- You must span the correct number of rows/columns on the parent grid item for subgrid to work as expected.
Context
Card grids or multi-column layouts where child elements need cross-card alignment.
Revisions (0)
No revisions yet.