Sub topic 1
CSS Subgrid: Aligning Nested Grids to Their Parent Tracks
Prerequisites
You should know CSS selectors, the box model, and basic CSS Grid. In particular, this chapter assumes display: grid, track sizing with fr, gap, and placement with grid-column, grid-row, and span.
Quick recap of grid tracks, lines and spanning
A grid track is a column or row in a grid. Grid lines mark the boundaries between tracks. A three-column grid has four column lines, numbered 1 through 4.
A grid item can span multiple tracks. For example, grid-column: 1 / 3 places an item across the first two columns. The ending line is not included.
.layout {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
gap: 1rem;
}
.header {
grid-column: 1 / -1;
}Here, -1 means the final grid line, so .header spans all three columns.
Why nested grids do not line up
A nested grid is a grid item that also has display: grid. By default, it creates a new, independent grid. Its columns are calculated from its own contents, not from the parent grid's tracks.
This can misalign repeated sections. For example, two cards might have different title lengths, so their body content starts at different vertical positions. A nested grid cannot automatically see or reuse the parent grid's column sizes.
The `subgrid` keyword
subgrid tells a nested grid to use tracks from its parent in a chosen axis. Use it as the value of grid-template-columns or grid-template-rows.
.cards {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}
.card {
display: grid;
grid-column: span 1;
grid-template-rows: subgrid;
}The row example works when the cards participate in parent row tracks. You can also use grid-template-columns: subgrid to inherit columns.
How a subgrid borrows its parent’s tracks
A subgrid must span the parent tracks it needs. Then its children occupy those inherited tracks.
.cards {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
}
.card {
display: grid;
grid-column: span 1;
grid-template-rows: subgrid;
grid-row: span 3;
}
.card > h2 { grid-row: 1; }
.card > p { grid-row: 2; }
.card > a { grid-row: 3; }Each card spans three parent rows and reuses them. Therefore, all headings, paragraphs, and links align across cards.
Exercise
Why must a card span the parent rows before grid-template-rows: subgrid can align its children?
Show answer
The subgrid can borrow only the parent tracks covered by its own grid area.