CSS
Aligned Nested Components using CSS Subgrid
Utilize the powerful CSS `subgrid` feature to create perfectly aligned nested grid layouts, allowing child grids to inherit and align with the parent grid's tracks and gaps.
.parent-grid {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: auto auto;
gap: 20px;
padding: 20px;
border: 2px solid #5cb85c;
}
.header-area {
grid-column: 1 / -1;
background-color: #dff0d8;
padding: 10px;
text-align: center;
}
.nested-grid-wrapper {
grid-column: 2 / 3;
display: grid;
grid-template-columns: subgrid;
grid-template-rows: auto;
gap: 10px;
border: 1px dashed #428bca;
padding: 10px;
}
.nested-item-1 {
grid-column: 1 / 2;
background-color: #fcf8e3;
padding: 10px;
}
.nested-item-2 {
grid-column: 2 / 3;
background-color: #f2dede;
padding: 10px;
}
.footer-area {
grid-column: 1 / -1;
background-color: #d9edf7;
padding: 10px;
text-align: center;
}
How it works: This snippet showcases `subgrid`, a valuable CSS Grid feature for aligning nested elements with their parent grid's tracks. By setting `grid-template-columns: subgrid` (or `grid-template-rows: subgrid`) on a grid item that is also a grid container, its direct children can use the parent's defined column (or row) tracks. This ensures perfect alignment and consistent spacing across complex, multi-layered grid layouts, simplifying design and maintenance.