CSS
CSS Grid: Align Nested Grids with `subgrid`
Learn to use CSS `subgrid` to perfectly align child elements with the parent grid tracks, ensuring consistent spacing and structure in complex layouts.
.parent-grid {
display: grid;
grid-template-columns: 1fr 200px 1fr;
grid-template-rows: auto 1fr auto;
gap: 20px;
}
.child-container {
grid-column: 2 / 4; /* Child spans columns 2 and 3 of parent */
display: grid;
grid-template-columns: subgrid; /* Inherit parent's columns */
grid-template-rows: auto; /* Define its own rows */
}
.child-item {
/* This item will align with the parent's column 3 */
grid-column: 3;
background-color: lightblue;
padding: 10px;
}
How it works: `subgrid` is a powerful CSS Grid feature that allows a nested grid container to inherit the track sizing from its parent grid. In this example, `.child-container` spans two columns of `.parent-grid`. By setting `grid-template-columns: subgrid;`, the child container's grid lines perfectly align with the parent's grid lines within its allocated space, making it easy to align its own children (`.child-item`) to the parent's grid structure.