CSS1 min read
Stop Using Margins for Spacing
The gap property is the modern way to space flex and grid items
S
Shahar Amir
Stop Using Margins for Spacing
Still doing this?
css
12345678
.card { margin-right: 16px; margin-bottom: 16px;}
.card:last-child { margin-right: 0;}There's a much better way.
The gap Property
css
1234
.container { display: flex; gap: 16px;}Done. No margin hacks. No :last-child fixes.
Why gap Wins
Before (margins):
- Extra margin on edges
- Need to remove last item's margin
- Complicated with wrapping
After (gap):
- Only adds space between items
- Works perfectly with flex-wrap
- One line of code
Works With Grid Too
css
12345
.grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px;}Different Row & Column Gaps
css
123456789
.container { gap: 16px 24px; /* row-gap column-gap */}
/* Or separate properties */.container { row-gap: 16px; column-gap: 24px;}Browser Support
100% support in all modern browsers. IE11 is dead. Use gap.
Margins for spacing between flex/grid items is legacy code. Upgrade today.
#flexbox#grid#layout
Stay Updated 📬
Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.