How subgrid allows nested grids to inherit their parent's grid tracks
Using grid-template-rows: subgrid and grid-template-columns: subgrid
Solving the alignment problem in card grids and form layouts
Understanding when to use subgrid vs nested grids
Creating perfectly aligned nested grid content without manual synchronization
Best practices for subgrid implementation
Introduction to Subgrid
Subgrid is a powerful CSS Grid feature that allows grid items to inherit the grid tracks (rows or columns)
of their parent grid. This solves a longstanding problem: aligning nested grid content across siblings.
Before subgrid, keeping elements like card footers or form labels aligned required complex workarounds
or JavaScript.
With subgrid, a grid item can declare display: grid; grid-template-rows: subgrid; and its
children will align to the parent's row tracks. This creates perfect alignment without manual coordination,
making complex layouts like card grids and forms much simpler to implement.
The Problem: Without Subgrid
Consider a card grid where each card has a title, description, and button. Without subgrid, cards with
different content lengths will have misaligned buttons—each card creates its own independent grid.
Example Without Subgrid
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}
.card {
display: grid;
grid-template-rows: auto 1fr auto;
/* Each card has its own grid - buttons won't align! */
}
Result: Misaligned Elements
Notice how the buttons appear at different heights because each card's grid is independent.
The Solution: With Subgrid
By using subgrid, the cards inherit the parent's grid rows, ensuring perfect alignment of titles,
content, and buttons across all cards regardless of content length.
Syntax
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}
.card {
display: grid;
grid-template-rows: subgrid; /* Inherit parent's rows! */
grid-row: span 3; /* Span 3 rows of parent */
}
/* Now children align across all cards */
.card h3 { /* All titles in row 1 */ }
.card p { /* All content in row 2 */ }
.card button { /* All buttons in row 3 - perfectly aligned! */ }
Example
<div class="grid">
<article class="card">
<h3>Short Title</h3>
<p>Brief content.</p>
<button>Action</button>
</article>
<article class="card">
<h3>Much Longer Title That Wraps</h3>
<p>Longer content that takes more space.</p>
<button>Action</button>
</article>
<article class="card">
<h3>Medium Title</h3>
<p>Medium content.</p>
<button>Action</button>
</article>
</div>
Result: Perfect Alignment
All buttons now align horizontally thanks to subgrid!
Subgrid on Columns
While subgrid is often used for row alignment, you can also use it for columns. This is particularly
useful for form layouts where you want labels and inputs to align across multiple form sections.