Topic 25 of 30
Grid Advanced
Overview
Advanced CSS Grid techniques include subgrid (aligning nested grids), auto-placement algorithms, named lines, and the minmax() function. These enable complex layouts that previously required JavaScript.
Syntax
css
/* Named lines */
.layout {
grid-template-columns: [sidebar-start] 250px [sidebar-end content-start] 1fr [content-end];
}
.main-content { grid-column: content-start / content-end; }
/* auto-fill vs auto-fit */
/* auto-fill: empty columns take space */
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
/* auto-fit: empty columns collapse */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
/* Dense packing */
grid-auto-flow: dense; /* fills holes in grid */
/* Subgrid */
.parent {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.child {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid; /* inherits parent's tracks */
}Common Pitfalls
- grid-column: -1 refers to the last explicit grid line — useful for making an item span the full width.
- auto-fill creates empty columns; auto-fit collapses them — use auto-fit for responsive grids without empty gaps.
- Interview tip: grid-auto-flow: dense fills holes caused by spanning items — perfect for masonry-like layouts.
Real-World Example
A magazine-style asymmetric layout using grid placement:
example
css
/* Magazine layout */
.magazine {
display: grid;
grid-template-columns: repeat(6, 1fr);
grid-auto-rows: 200px;
gap: 16px;
}
/* Featured article spans multiple columns and rows */
.article-featured {
grid-column: 1 / 4;
grid-row: 1 / 3;
}
/* Secondary articles */
.article-secondary { grid-column: span 2; }
.article-small { grid-column: span 1; }
/* Auto-responsive without media queries */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 280px), 1fr));
gap: 24px;
}
/* Holy Grail Layout */
.holy-grail {
display: grid;
grid-template:
"header header header" 64px
"nav main aside" 1fr
"footer footer footer" 48px
/ 200px 1fr 160px;
min-height: 100vh;
}