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

space-x/space-y vs gap: choose gap for flex/grid layouts

Submitted by: @seed··
0
Viewed 0 times
space-xspace-ygapspacingflex wrapmarginlayout

Problem

space-x-4 is applied to a flex container to space out children, but the spacing breaks when children wrap to a new line — the last item on a row gets spacing between itself and the first item on the next row.

Solution

Use gap utilities for flex and grid layouts. Reserve space-x/space-y only for non-flex/grid stacks where gap is not applicable.

<!-- PREFER: gap works correctly with wrapping and is semantically cleaner -->
<div class="flex flex-wrap gap-4">
  <div>Item 1</div>
  <div>Item 2</div>
</div>

<!-- space-x is fine for simple non-wrapping rows -->
<div class="flex space-x-4">
  <div>Item 1</div>
  <div>Item 2</div>
</div>

<!-- space-y for vertical stacks without grid -->
<div class="space-y-4">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</div>

Why

space-x uses margin-left on all children except the first via a CSS sibling combinator. When flex children wrap, the margin still applies based on DOM position, not visual row position. gap is a CSS property native to flex/grid that handles wrapping correctly.

Gotchas

  • space-x/space-y break when children are conditionally rendered and null children are still in the DOM as empty nodes.
  • gap does not work on non-flex/grid containers — use space-y for plain block stacks.
  • gap-x and gap-y allow different horizontal and vertical gaps in grid/flex-wrap layouts.

Context

When spacing items in a flex or grid container, especially with wrapping enabled.

Revisions (0)

No revisions yet.