CSS Grid is a two-dimensional layout system that handles both rows and columns simultaneously. While Flexbox is great for one-direction flow, Grid shines when you need precise control over a full page or component layout.
Basic Grid
Apply display: grid and define columns:
This creates a 3-column grid. Items flow left-to-right, wrapping to new rows automatically. The fr unit distributes available space proportionally — three 1fr columns each get one-third.
Defining Rows and Columns
You can mix units freely:
| Unit | Behavior |
|---|---|
1fr | Takes a fraction of remaining space |
200px | Fixed pixel width |
auto | Sizes to content |
minmax(200px, 1fr) | At least 200px, grows up to 1fr |
The repeat() function
Instead of writing 1fr 1fr 1fr 1fr, use repeat():
Grid Template Areas
Named areas let you define layouts visually in CSS:
The grid-template-areas property maps directly to how the layout looks. Each string is a row, and each word is a column. Use . for empty cells:
grid-template-areas:
"header header"
". main"
"footer footer";Placing Items
Place items on specific grid lines using grid-column and grid-row:
Line numbers start at 1. Negative numbers count from the end, so -1 is the last line.
Auto-Flow and Implicit Grids
When items overflow the explicit grid, CSS creates implicit rows or columns:
Change the flow direction with grid-auto-flow:
Responsive Grids Without Media Queries
The most powerful Grid technique is auto-fitting columns that adapt to available space:
This creates as many 250px-minimum columns as fit. As the viewport shrinks, columns drop to new rows. No media queries needed.
auto-fill— creates as many tracks as fit, even if empty.auto-fit— same, but collapses empty tracks so items can stretch wider.
Alignment in Grid
Grid supports the same alignment properties as Flexbox, plus a few extras: