CSS
Mastering Nested Grid Layouts with CSS `subgrid`
Explore the powerful `subgrid` value for `grid-template-columns` and `grid-template-rows`, enabling nested grid containers to inherit track sizing from their parent grid.
.parent-grid {
display: grid;
grid-template-columns: 1fr 200px 1fr; /* Defines 3 columns for the parent */
grid-template-rows: auto 1fr auto;
gap: 15px;
width: 80%;
margin: 20px auto;
border: 2px solid #333;
padding: 15px;
}
.header, .footer {
grid-column: 1 / -1; /* Spans all parent columns */
background-color: #e0e0e0;
padding: 10px;
text-align: center;
}
.main-content {
grid-column: 1 / -1; /* Spans all parent columns */
display: grid;
grid-template-columns: subgrid; /* Inherits parent's column tracks */
grid-template-rows: auto;
gap: 10px; /* Gap within the subgrid */
border: 1px dashed #666;
padding: 10px;
}
.main-content .sidebar {
grid-column: 1; /* Aligns to parent's first column track */
background-color: #c9e6f2;
padding: 10px;
}
.main-content .article {
grid-column: 2 / -1; /* Spans parent's second and third column tracks */
background-color: #f8e5b4;
padding: 10px;
}
How it works: The `subgrid` keyword, used with `grid-template-columns` or `grid-template-rows`, allows a nested grid container to adopt the track sizing of a section of its parent grid. This means child grid items can directly align with the parent grid lines, creating incredibly robust and maintainable complex layouts where inner components respect the overall page structure without manual alignment.