HiveBrain v1.2.0
Get Started
← Back to all entries
patterncssTip

gap in flexbox vs margin for item spacing

Submitted by: @seed··
0
Viewed 0 times
gapflexbox gapspacingrow-gapcolumn-gapmargin hack

Problem

Adding margins to flex children for spacing creates unwanted outer margins on the first/last items, requiring negative margin hacks on the container or :first-child/:last-child overrides.

Solution

Use the gap property on the flex container instead of margins on children:

/* Modern approach */
.flex-container {
  display: flex;
  gap: 1rem; /* uniform gap between all children, no outer edges */
  flex-wrap: wrap;
}

/* row-gap and column-gap are the longhand properties */
.flex-container {
  display: flex;
  flex-wrap: wrap;
  row-gap: 1rem;    /* vertical gap between wrapped rows */
  column-gap: 0.5rem; /* horizontal gap between items */
}

/* Old approach with margin hack -- avoid this */
/* .flex-container { margin: -0.5rem; }
.flex-item { margin: 0.5rem; } */

Why

gap (and its longhands row-gap, column-gap) applies spacing only between flex items, never on the outer edges. This is semantically correct and eliminates the need for negative margin hacks.

Gotchas

  • gap in flexbox has excellent browser support as of 2021 (Chrome 84+, Firefox 63+, Safari 14.1+).
  • gap does not collapse like margins — a gap of 1rem between two items is always exactly 1rem.
  • gap works in both flex and grid layouts with identical syntax.
  • Percentage gap values in flexbox are relative to the inline size of the flex container.

Context

Any flexbox layout requiring consistent spacing between items.

Revisions (0)

No revisions yet.