Learn CSS Grid to build two-dimensional layouts with rows and columns. Master grid-template-columns, the fr unit, repeat(), gap, and item placement to create complex page layouts.
CSS Grid is a two-dimensional layout system — unlike Flexbox which handles one axis at a time, Grid lets you control both rows and columns simultaneously.
To create a grid, set display: grid on a container. Then define your column and row tracks with grid-template-columns and grid-template-rows.
.grid {
display: grid;
grid-template-columns: 200px 200px 200px;
grid-template-rows: 100px 100px;
gap: 16px;
}This creates a grid with 3 columns (each 200px wide) and 2 rows (each 100px tall), with 16px of spacing between all cells.
The gap property works exactly like in Flexbox — it adds spacing between grid tracks without affecting the outer edges. You can also use column-gap and row-gap separately.
/* The fr unit distributes available space proportionally */
.grid-fractional {
display: grid;
/* 1st column gets 1 share, 2nd gets 2 shares */
grid-template-columns: 1fr 2fr;
gap: 16px;
}
/* repeat() avoids writing the same value multiple times */
.grid-repeat {
display: grid;
/* Creates 3 equal columns */
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}
/* Mix fixed and flexible tracks */
.grid-mixed {
display: grid;
/* Fixed sidebar, flexible main, fixed aside */
grid-template-columns: 250px 1fr 200px;
gap: 16px;
}
/* Auto-fill creates as many columns as fit */
.grid-auto {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 16px;
}By default, grid items fill cells in order from left to right, top to bottom. But you can place items in specific cells using grid-column and grid-row.
Grid lines are numbered starting from 1 (not 0). A 3-column grid has 4 column lines: 1, 2, 3, 4.
.header {
grid-column: 1 / 4; /* span from line 1 to line 4 (all 3 columns) */
}
.sidebar {
grid-row: 2 / 4; /* span rows 2 and 3 */
}
/* Shorthand with span keyword */
.wide-item {
grid-column: span 2; /* span 2 columns from current position */
}The grid-column property is shorthand for grid-column-start / grid-column-end. The span keyword is a convenient way to say "take up N tracks" without calculating exact line numbers.
For complex layouts, you can also use named grid areas with grid-template-areas, but line-based placement is the foundation you should master first.
What does `grid-template-columns: repeat(3, 1fr)` create?