DevPath · Learn to code ESPTEN

CSS Grid

Basic grid: rows, columns and the fr unit

From one dimension to two

Picture designing the front page of a newspaper: headline up top, several columns of text, a photo that spans two of them, the footer below. That's laying out in 2D, and it's exactly what Grid makes easy.

Flexbox distributes elements along one axis (a row or a column). CSS Grid works in two dimensions at once: rows and columns. It is the right tool when you want to align content both horizontally and vertically, whether it's a dashboard, a photo gallery or a full-page layout.

Activating the grid

The layout lives in the container: as soon as you give it display: grid, its direct children become grid items and are placed inside the grid. The container defines the structure; the items occupy it.

.gallery {
  display: grid;
  grid-template-columns: 200px 200px 200px;  /* 3 columns of 200px */
}

The fr unit: fractions of the free space

Fixed measures (px) are rigid: on a narrow screen they overflow. The fr unit (fraction) distributes the available space in proportions, like slicing a pie into portions. 1fr 1fr 1fr creates three columns that share the width equally and adapt to the container's size.

⚠️ CLASSIC TRAP: 1fr is not "a fixed third". It's a fraction of what's left over. If one column holds wide content, fr shares out whatever remains after that, not the total. So 1fr 1fr may not end up as two identical columns when the content takes charge.

.gallery {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;  /* 3 equal, flexible columns */
  grid-template-rows: 100px auto;      /* fixed row + growing row */
}

You can mix units: grid-template-columns: 250px 1fr; leaves a fixed column of 250px (a sidebar) and another that takes the rest.

Spacing between cells: gap

gap is the spacing between cells, without having to add margin to each item (Grid margins don't collapse and don't overflow on the sides):

.gallery {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 16px;             /* 16px between rows and columns */
}

Mental rule: the container is the architect that draws the grid's blueprints (display, columns, rows, gap); the items are the tenants that only decide which slot they move into.

Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Placing items: lines, span and areas →