A Taste of Grid

Rows and columns without the headache

7 min read

Flexbox is wonderful for laying things out in a single row or column. But what if you want a true grid, like a photo gallery with three columns and as many rows as needed? CSS has a second layout system built exactly for that, and it is called grid.

Your first grid

Just like flexbox, grid works by styling a container. Suppose your HTML is a gallery of six images or cards inside a container:

<div class="gallery">
  <div class="item">One</div>
  <div class="item">Two</div>
  <div class="item">Three</div>
  <div class="item">Four</div>
  <div class="item">Five</div>
  <div class="item">Six</div>
</div>

Then the CSS:

.gallery {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 16px;
}

That is the whole thing. The six items arrange themselves into three columns and two rows, with 16px of space between everything. Items flow into the grid automatically, left to right, top to bottom, like words filling lines on a page.

What is fr?

The fr unit means "fraction of the available space". Writing 1fr 1fr 1fr says "make three columns and give each one an equal share". The magic is that the columns share whatever space exists, so the grid stretches and shrinks with the page on its own.

Fractions do not have to be equal. This makes a wide main column with a narrower sidebar:

.page-layout {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
}

The first column gets two shares of the space and the second gets one, so it is a two-thirds and one-third split. Change the numbers, change the proportions. No math required.

A shortcut for repeated columns

Typing 1fr 1fr 1fr 1fr gets old. The repeat() function says the same thing more neatly:

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

Grid or flexbox?

A simple way to choose: if you are lining things up in one direction, a single row or a single column, reach for flexbox. If you are arranging things in two directions at once, rows and columns together, reach for grid. Most real websites use both: grid for the big page structure, flexbox for the small stuff inside, like a row of buttons. There is plenty more depth to each, but honestly, display: grid plus grid-template-columns plus gap already covers a huge share of what real sites need.

Grid is one of the newest and friendliest parts of CSS. Developers who fought with layouts for years describe grid as the feature they wished they had all along. You get to start with it from day one.

Quick check

Q1 What does grid-template-columns: 1fr 1fr 1fr; create?

Q2 You want a photo gallery with 3 columns and many rows. Which tool fits best?

Want to save your progress? It's free.

Create a free account