CSS
Seamlessly Aligning Nested Grids with `subgrid`
Master `subgrid` to effortlessly align content within nested CSS Grid layouts, inheriting parent track definitions for pixel-perfect vertical and horizontal consistency.
.parent-grid {
display: grid;
grid-template-columns: 1fr 200px 1fr; /* Parent defines 3 columns */
grid-template-rows: auto 100px auto; /* Parent defines 3 rows */
gap: 15px;
width: 90%;
margin: 30px auto;
border: 2px solid #28a745;
padding: 15px;
font-family: sans-serif;
}
.parent-item {
background-color: #e6ffe6;
padding: 10px;
border: 1px solid #5cb85c;
text-align: center;
}
.parent-item.with-subgrid {
/* Place this item into the middle cell of the parent */
grid-column: 2;
grid-row: 2;
background-color: #c8e6c9;
display: grid;
/* Inherit parent column tracks from its own cell */
grid-template-columns: subgrid;
/* Inherit parent row tracks from its own cell */
grid-template-rows: subgrid;
gap: 5px; /* Separate gap for subgrid items */
padding: 10px;
border: 2px dashed #4CAF50;
}
.subgrid-item {
background-color: #a8d7a8;
padding: 8px;
border: 1px solid #66bb6a;
font-size: 0.9em;
}
How it works: The `subgrid` keyword revolutionizes nested grid layouts by allowing a child grid to inherit and align perfectly with its parent's track definitions. Instead of defining its own `grid-template-columns` or `grid-template-rows`, a subgrid item leverages the existing tracks of the cell (or area) it occupies within the parent grid. This example demonstrates how to place a subgrid within a single cell of a parent grid, ensuring internal items perfectly align with the parent's structural lines, which is crucial for maintaining consistent alignment across complex, nested designs.