Subgrid
Subgrid allows a nested grid to adopt the track sizing of its parent grid. This solves the classic alignment problem where items inside nested grids couldn't align with items in the parent.
1. The Problem Subgrid Solves
Without subgrid, if you have cards in a grid, internal elements inside each card can't align across cards β each card has its own independent coordinate system.
/* Without subgrid β titles can't align across cards */ .grid { grid-template-columns: repeat(3, 1fr); } .card { display: flex; flex-direction: column; /* or display: grid, but with its own rows */ /* internal elements align within card, */ /* NOT across cards in the parent grid */ }
2. Subgrid β Inherit Parent Tracks
With subgrid, a nested grid item can inherit its parent's column or row tracks. Items inside the nested grid participate in the parent grid β enabling cross-card alignment.
.grid {
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto auto auto;
}
.card {
display: grid;
grid-row: span 3; /* span 3 parent rows */
grid-template-rows: subgrid; /* adopt parent rows! */
gap: 8px;
}
/* Now card children align across all cards */3. Subgrid on Columns
You can also apply subgrid to columns. A nested grid item that spans multiple columns can let its children align to the parent column lines.
col 1
col 4
.grid {
grid-template-columns: repeat(4, 1fr);
}
.subgrid-item {
grid-column: 1 / -1; /* span all columns */
display: grid;
grid-template-columns: subgrid; /* adopt parent cols */
}
/* children align to parent grid columns */
.child-b { grid-column: span 2; }4. Subgrid for Both Axes
You can use subgrid for both columns AND rows simultaneously. The nested grid becomes a window into the parent grid's coordinate system.
.parent {
grid-template-columns: repeat(3, 1fr);
grid-template-rows: 50px 50px 50px;
}
.nested {
grid-column: 2 / 4; /* span 2 parent cols */
grid-row: 2 / 4; /* span 2 parent rows */
display: grid;
grid-template-columns: subgrid; /* inherit 2 cols */
grid-template-rows: subgrid; /* inherit 2 rows */
}