CodeBlanks Logo Icon CodeBlanks

Gap

CSS course · Intermediate · Lesson 11/98

Learn the gap between flex items with gap.

What is gap?

The gap property sets the space between flex items. It replaces margins; you no longer need to write a margin on each item. With gap: 1rem, all items sit 1 rem apart.

gap only works between items; it adds no space before the first item or after the last. This makes it more predictable than margins.

row-gap and column-gap

gap can also be written as two separate properties. row-gap sets the space between rows, column-gap between columns. With one value, the gap shorthand applies to both.

With two values, the first is row-gap and the second is column-gap: gap: 1rem 2rem. This is ideal for adjusting row spacing in a wrapping flex layout.

Exercise Add gap to a card layout

Set up a .cards flex container. Add display: flex, flex-wrap: wrap and gap: 1rem. When the cards wrap, they keep 1 rem of space between them.

Show example solution
/* space the cards apart */
.cards {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

Test yourself

  1. Where is the gap property written?

    • On each flex item separately
    • Only on the flex container
    • Only on the first item
    • On the HTML root element
    Show answer

    Only on the flex container — Correct. gap goes on the container and applies to all items automatically.

  2. Write the gap: 1rem 2rem declaration

    .grid {
      display: flex;
      flex-wrap: wrap;
      ____: 1rem 2rem;
    }
    Show answer
    .grid {
      display: flex;
      flex-wrap: wrap;
      gap: 1rem 2rem;
    }
  3. Match each property to its scope

    gap
    Both row and column spacing
    row-gap
    Only row spacing
    column-gap
    Only column spacing
    gap: 1rem
    1 rem in both directions

All lessons in Intermediate