← CSS tutorial

CSS

Grid

While flexbox is great for laying out one row (or one column) at a time, display: grid lays things out in rows and columns at once — a genuinely two-dimensional layout tool.

Example: a photo gallery grid

.gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

grid-template-columns: repeat(3, 1fr) creates three equal columns (1fr means "one fraction of the available space," so three of them split it evenly). Items simply flow into the grid left to right, top to bottom, automatically wrapping to a new row once a row fills up — you never manually decide which item goes on which row.

Choosing between flexbox and grid

A useful rule of thumb: reach for flexbox when you're arranging items along a single line that may wrap (a row of tags, a nav bar), and reach for grid when you're deliberately laying things out in both rows and columns together (a photo gallery, a dashboard layout, a page's overall structure). Many real interfaces use both at once — grid for the overall page structure, flexbox inside individual grid cells.

Try it yourself