CSS Grid Layout: The Definitive Guide
Master CSS Grid with practical examples — from basic grid definitions to complex responsive layouts without media queries.
Why CSS Grid?
CSS Grid is a two-dimensional layout system. Unlike Flexbox (which handles one axis at a time), Grid controls both rows and columns simultaneously. It is the right tool for page-level layouts, card grids, and any design where you need precise control over both dimensions.
Defining a Grid
.grid {
display: grid;
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
gap: 1rem;
}
This creates a three-column layout: fixed sidebars with a flexible center. The fr unit distributes available space proportionally.
The fr Unit
The fr (fraction) unit represents a share of the available space after fixed sizes are allocated:
/* Equal thirds */
grid-template-columns: 1fr 1fr 1fr;
/* Sidebar + main content */
grid-template-columns: 250px 1fr;
/* 1:2:1 ratio */
grid-template-columns: 1fr 2fr 1fr;
repeat() and Auto-Fill
/* 12-column grid */
grid-template-columns: repeat(12, 1fr);
/* Responsive cards — no media queries! */
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
/* auto-fit stretches items to fill space */
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
The auto-fill vs auto-fit distinction: auto-fill creates empty tracks to fill the row; auto-fit collapses empty tracks so items stretch wider.
Grid Areas
Named grid areas create readable, visual layouts:
.layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar content aside"
"footer footer footer";
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.content { grid-area: content; }
.aside { grid-area: aside; }
.footer { grid-area: footer; }
Placing Items
/* Span columns */
.wide { grid-column: 1 / -1; } /* full width */
.half { grid-column: span 2; } /* two columns */
/* Span rows */
.tall { grid-row: span 3; }
/* Exact placement */
.feature {
grid-column: 2 / 4;
grid-row: 1 / 3;
}
Alignment
/* Align all items */
.grid {
justify-items: center; /* horizontal within cell */
align-items: center; /* vertical within cell */
place-items: center; /* shorthand for both */
}
/* Align individual item */
.item {
justify-self: end;
align-self: start;
}
Responsive Without Media Queries
The combination of auto-fill and minmax() creates responsive grids that adapt without a single media query:
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1.5rem;
}
Cards are at least 300px wide, fill available space, and wrap to new rows automatically.
Summary
CSS Grid and Flexbox are complementary. Use Grid for two-dimensional layouts (pages, card grids, dashboards). Use Flexbox for one-dimensional alignment (navbars, button groups, inline elements). Master both.