Course contentsShow
← Web Development
Lesson 279 of 2,9825. FlexboxFree lesson

gap: Modern Spacing Between Flex Items

Use the gap property (row-gap and column-gap) to add consistent spacing between flex items without margins.

gap: Modern Spacing Between Flex Items

You'll learn how to add clean, consistent spacing between flex items without wrestling with margins.

Why gap Changes Everything

Before gap, adding space between flex items meant applying margins to each item—then dealing with unwanted margin at the container edges or using complex :not(:last-child) selectors. The gap property solves this elegantly by adding space between items only, never at the outer edges.

Think of gap like the grout between tiles: it creates separation between pieces without adding extra space around the entire surface.

Using gap in Flexbox

Simply apply gap to the flex container (not individual items):

.container {
  display: flex;
  gap: 20px; /* 20px space between all items */
}

This creates consistent spacing between items in both directions when they wrap or stack.

Directional Control

You can control spacing separately for rows and columns:

.container {
  display: flex;
  flex-wrap: wrap;
  row-gap: 30px;    /* vertical spacing */
  column-gap: 15px; /* horizontal spacing */
}

Or use the shorthand:

.container {
  display: flex;
  gap: 30px 15px; /* row-gap column-gap */
}

Why This Matters

  • No margin math: No need to calculate negative margins on the container or selectively apply margins
  • Dynamic: Works automatically as items wrap or change direction
  • Clean edges: The container's padding remains undisturbed
  • Responsive-friendly: Change gap at breakpoints without touching individual items

Key Takeaway: Use gap on flex containers to add consistent spacing between items without margins—it only affects the space between items, never at the outer edges.