CSS Grid
~310 words ยท 2 min read
Grid: two-dimensional layout
CSS Grid arranges items in rows and columns simultaneously โ ideal for full page layouts, dashboards, and galleries. Apply display: grid and define your tracks.
Defining tracks
.grid {
display: grid;
grid-template-columns: 200px 1fr 1fr;
grid-template-rows: auto 1fr auto;
gap: 1rem;
}
The fr unit
fr stands for "fraction of the remaining space". Two 1fr columns split available space equally; a 2fr column takes twice as much as a 1fr one. Unlike percentages, fr accounts for gaps automatically.
Spanning cells
Items can span multiple tracks:
.hero {
grid-column: 1 / 4; /* columns 1 through 3 */
grid-row: 1 / span 2; /* span 2 rows */
}
Responsive grids without media queries
Combine minmax() with auto-fit to get a grid that wraps automatically:
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
}
Each column is at least 220px; extra columns are added or removed as the viewport widens or narrows โ with zero media queries.
auto-fit vs auto-fill
They look identical until the grid has fewer items than tracks. auto-fit stretches the existing items to fill empty tracks; auto-fill keeps empty tracks as gaps. Use auto-fit when items should grow to fill space.
Rule of thumb: reach for Flexbox for one-dimensional flows (a single row or column), and Grid when you need to control both rows and columns at once.