๐ŸŽ“ A1Learner
๐Ÿ”

CSS Grid

CSS Grid lays items into rows and columns at the same time. grid-template-columns sets the columns, called tracks, that the items flow into.

Three fixed columns

Three tracks of 100 pixels fill the 320 pixel list, with the gap between them. All three items land in the first row.

ul {
  display: grid;
  grid-template-columns: 100px 100px 100px;
  width: 320px;
  gap: 10px;
}

Columns in shares

The fr unit divides the free space into shares. Two shares take twice the width of one share.

ul {
  display: grid;
  grid-template-columns: 1fr 2fr;
  width: 300px;
}

Items wrap to a new row

Two columns hold two items. The third item flows into a second row on its own.

ul {
  display: grid;
  grid-template-columns: 150px 150px;
  width: 310px;
  gap: 10px;
}

Example

ul {
  display: grid;
  grid-template-columns: 100px 100px 100px;
  width: 320px;
  gap: 10px;
}
li {
  background-color: lightblue;
  text-align: center;
  padding: 6px;
}

Key points

  • Grid is two-dimensional, and flexbox works along one axis at a time
  • A track is one row or one column of the grid
  • The fr unit is a share of the free space in the container
  • Items place themselves into the tracks in order
  • gap sets the space between tracks in both directions

In this example, the list becomes a grid with three columns of 100 pixels each. gap leaves 10 pixels between the tracks. The items flow into the three columns of the first row. Each item gets a pale background, centred text and a little padding.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does the fr unit stand for?