Skip to main content
🎨 CSS as a design system·Module B2 · Lesson 8
TaskStyle a .toolbar with display: flex, gap: 8px. Five buttons inside, each padding 6px 12px, background #f5f5f5, border-radius 6px. No margin trickery — just gap.

gap: clean spacing without margin hacks

75 XP5 min
Theory

The right way to space flex/grid items

.row {
  display: flex;
  gap: 16px;          /* equal spacing between siblings */
}
.row {
  gap: 16px 8px;      /* row-gap col-gap (when wrapping) */
}

gap puts space BETWEEN siblings — not before the first, not after the last. Compare:

/* Old way — leading/trailing margin needs cleanup */
.row > * { margin-right: 16px; }
.row > *:last-child { margin-right: 0; }      /* ugh */

/* New way */
.row { gap: 16px; }                            /* done */

Works in grid + flex (and plain block since 2024)

gap started life in CSS Grid (2017), spread to Flexbox (2021), and as of 2024 even works on plain block containers in modern browsers. So the days of "margin-right except last child" hacks are over.

Two values

gap: 16px 24px is row-gap col-gap. When you wrap, vertical gaps between rows can be different from horizontal gaps between items.

.cards {
  display: flex;
  flex-wrap: wrap;
  gap: 20px 12px;     /* 20px between rows, 12px between cards in a row */
}

The mental shift

If you find yourself writing margin to space SIBLINGS, switch to gap on the parent. Use margin only for "this element's spacing from the world" (parent padding, neighboring sections).

🔒

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial — card required, cancel anytime.

Sign up — free trial →

First 10 lessons in each track are free. No card needed for those.

PreviousNext lesson →

Get one Python or web tip a day — by email

Short, hand-written, no spam. Unsubscribe in one click.