DEV3 Technologies home

DEV3 Developer Forum

Should I use gap or margins to space items in flexbox and grid? What about space-x in Tailwind?

dev3 ·

I used margins on every item and had to remove the last margin with :last-child or negative margins. A teammate says to use gap. Does gap work in flexbox and what are the Tailwind equivalents?

#css#gap#flexbox#tailwind

0

1 reply

dev3 · Accepted answer

Use gap

gap (with row-gap and column-gap) puts space only between items, never at the edges. It works in grid and in flexbox, in all current browsers.

.toolbar { display: flex; flex-wrap: wrap; gap: 0.75rem 1rem; } /* row column */
.cards   { display: grid;  grid-template-columns: repeat(3, 1fr); gap: 1.5rem; }

Compared with margins:

  • No edge spacing to remove, no :last-child rules.
  • Wrapped rows get correct vertical spacing automatically (margins with flex-wrap add the wrong space at line ends).
  • Direction-agnostic: works for rows, columns and RTL.

Tailwind

gap-4, gap-x-6 gap-y-2. These are the preferred utilities with flex and grid.

space-x-* / space-y-* use a sibling selector that adds margin to every child except the first. They also work on non-flex containers, but have drawbacks: broken with flex-wrap, break when children are hidden with hidden in some cases, and in Tailwind 4 the selector changed to :not(:last-child) (for performance), so hidden or reordered children can behave differently than in v3. Use flex flex-col gap-* instead of space-y-* when possible.

divide-y and divide-x add borders between items (lists, tables) and share this sibling behavior.

When margins are still right

  • Space between a heading and the paragraph that follows it (content flow, e.g. prose).
  • margin-inline: auto for centering or margin-left: auto to push an item.
  • Block layout with no flex/grid parent.

Pitfall

gap in a block container does nothing, the parent needs display: flex or display: grid (or multi-column).

To try combinations interactively, use the flexbox playground.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.