CSS Subgrid
CSS Subgrid is a feature of CSS Grid Layout that allows nested grids to participate in the sizing of their parent grid. It enables descendant elements to align to the tracks of the main grid, which was previously impossible without flattening the HTML structure.
1. The Problem
With standard CSS Grid, a grid container defines tracks (rows/columns). Its direct children place themselves on these tracks. However, if a child is also a grid container, its own children (grandchildren of the main grid) operate in an independent grid context. They cannot align with the outer grid's tracks.
2. The Solution: subgrid
By setting grid-template-columns or grid-template-rows to subgrid, you tell the nested grid to use the tracks defined on its parent, rather than defining its own.
.parent {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 20px;
}
.child {
display: grid;
grid-column: span 3;
/* Inherit the 3 columns from .parent */
grid-template-columns: subgrid;
}
3. Use Case: Card Layouts
A common issue is a row of cards where you want the headers, bodies, and footers to align horizontally across all cards, regardless of the content height in each section.
<div class="grid">
<div class="card">
<h3>Title</h3>
<p>Content...</p>
<footer>Footer</footer>
</div>
<!-- More cards... -->
</div>
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
/* Define rows for the cards' internals */
grid-auto-rows: auto 1fr auto;
}
.card {
display: grid;
grid-row: span 3; /* Span 3 rows of the parent */
grid-template-rows: subgrid; /* Use the parent's row sizing */
}
With subgrid, the "Content" row in the parent grid will expand to fit the tallest content across all cards, ensuring headers and footers stay perfectly aligned.
4. Browser Support
Subgrid is supported in modern versions of Firefox, Safari, and Chrome (from version 117).