CSS Grid
CSS grid builds real grids with columns and rows at the same time. Flexbox arranges items along one line; grid works in two dimensions. That makes it the right tool for whole page layouts, photo galleries, dashboards, and card walls where you want everything to line up on both axes.
You start by setting display: grid on a container, then you define the columns with grid-template-columns. Items snap into the grid left to right, row by row, in what is called auto placement. Add more items and the grid simply adds more rows. Everything stays aligned because the columns are fixed and shared.
The fr unit is the workhorse of grid. One fraction is a share of the leftover space after fixed-size tracks are placed. repeat(3, 1fr) means three equal columns. Fixed units like px are great for sidebars, but fr is what makes layouts stretch with the viewport. Grid and flexbox work well together: grid for the page, flexbox for the items inside.
Columns and rows
grid-template-columns defines the column widths; grid-template-rows defines the row heights. repeat() saves typing: repeat(3, 1fr) is the same as 1fr 1fr 1fr. Fixed units like 240px reserve exact space, and fr shares whatever is left. A classic dashboard uses a 240px sidebar and one fr column for the content, so the content always fills the remaining width.
.layout {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-rows: auto 1fr;
gap: 16px;
}
Making an item span
Auto placement fills the grid row by row, left to right. When you want one item to break the pattern, grid-column and grid-row let you place it deliberately. grid-column: 1 / 3 spans from line 1 to line 3, which covers two columns. The short form grid-column: span 2 means the same thing and reads easier. This is how a hero banner stretches across a whole grid.
.banner {
grid-column: span 2; /* stretches over two columns */
}
Grid versus flexbox
The rule of thumb: flexbox for one line of content, grid for two dimensions. A nav bar, a button row, or a tag list is flexbox territory. A photo gallery, a dashboard, or the skeleton of a whole page is grid territory. They are not rivals. Grid sets up the page frame, and flexbox arranges the items inside each cell. Reaching for grid when a simple row would do is a common overkill.
.page {
display: grid;
grid-template-columns: 1fr 2fr;
gap: 20px;
}
.toolbar {
display: flex;
gap: 8px;
}
Syntax
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}
repeat(3,1fr) Needs Gap or It Overflows
Grid without gap can overflow on mobile — add gap:16px and use minmax(0,1fr) for flex children.
grid-template-columns: repeat(3, minmax(0,1fr))
Good to know
- Grid handles rows and columns at once.
- repeat(3, 1fr) makes three equal columns.
- fr shares leftover space; px reserves fixed space.
- Use grid for page layout, flexbox for single lines.