Subgrid Patterns
You'll learn how to align nested grid items with their parent grid's lines using the subgrid keyword.
What Is Subgrid?
Sometimes you have a grid item that is itself a grid container. By default, this nested grid is completely independent—its columns and rows don't align with the parent grid's tracks. The subgrid value lets a nested grid inherit its parent's column or row lines, creating perfect alignment across multiple levels.
Think of it like graph paper: normally, if you draw a smaller grid inside one square, its lines won't match the main grid. Subgrid forces the inner grid to use the same lines as the outer one.
Using Subgrid
When you set grid-template-columns: subgrid or grid-template-rows: subgrid on a grid item that is also a grid container, it adopts the parent's track structure for that axis:
.parent-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}
.nested-grid {
display: grid;
grid-column: 1 / 4; /* spans all 3 columns */
grid-template-columns: subgrid; /* inherits parent's 3 columns */
}
Now items inside .nested-grid align perfectly with the parent's column lines—great for card headers, footers, or form fields that need to line up across rows.
When to Use Subgrid
Subgrid shines in patterns like card grids where each card has internal elements (image, title, description, button) that should align vertically across all cards, or complex forms where labels and inputs need consistent alignment regardless of nesting depth.
Key Takeaway:
Use subgrid to make nested grids inherit their parent's grid lines, ensuring perfect alignment across multiple layout levels.