CodeBlanks Logo Icon CodeBlanks

Grid gap

CSS course · Intermediate · Lesson 37/98

Learn the gap between grid cells with gap.

Space between cells

Grid cells sit next to each other by default. To put space between them you use the gap property; the same name you know from Flexbox. gap: 16px adds 16 pixels between both rows and columns.

You can also write two values instead of one: gap: 16px 8px. The first value is the row gap, the second is the column gap. Order matters: row first, then column.

row-gap and column-gap

Sometimes you want to set row and column spacing separately. For that, use row-gap and column-gap. row-gap: 24px; column-gap: 12px makes rows wide and columns narrow.

The gap: 24px 12px shorthand means the same: first value is row-gap, second is column-gap. The two forms are equivalent; which one you pick is a style choice.

Exercise Add spacing to the gallery

The .gallery already contains display: grid and grid-template-columns: repeat(3, 1fr). Add a gap: 20px declaration so the photos get 20 pixels of breathing room.

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

Test yourself

  1. What does gap: 12px do?

    .gallery {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 12px;
    }
    • Adds 12px padding to every cell
    • Puts 12px only between rows
    • Puts 12px only between columns
    • Puts 12px between both rows and columns
    Show answer

    Puts 12px between both rows and columns — Correct. A single gap value puts the same space between both rows and columns; here 12px.

  2. Wide rows, narrow columns

    .cards {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: ____;
    }
    Show answer
    .cards {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 16px 8px;
    }
  3. Match each gap declaration to its meaning

    gap: 12px
    Both axes 12px
    gap: 16px 8px
    Row 16, column 8
    row-gap: 20px
    Only row 20px
    column-gap: 4px
    Only column 4px

All lessons in Intermediate