Layout Beginner

Spacing elements without margin hacks

The old way used margins on children and negative margin on the container, or :last-child to cancel the last margin. Gap handles it on the parent.

3 lines
1.grid {
2  display: flex;
3  gap: 16px;
4}
Old 6 lines
1.grid {
2  display: flex;
3}
4
5.grid > * {
6  margin-right: 16px;
7}
8.grid > *:last-child { margin-right: 0; }
Widely available Since 2021 95% global usage

This feature is well established and works across many devices and browser versions. It has been available across browsers since 2021.

84+
63+
14.1+
84+
gap handles all the spacing
1
2
3
4
5
6
7
8
display: flex; gap: 12px;
Kinsta

Your first month is free

Managed WordPress hosting for faster sites.

Learn more
⚑

No edge cases

Gap only goes between items. No need to zero out the last child or use negative margins.

✦

Parent controls spacing

One value on the container. Add or remove children, spacing stays consistent.

∞

Flex and grid

Same gap property works for both. Row and column gap available too.

Lines Saved
6 β†’ 3
50% less code
Old Approach
Margin on children
:last-child override
Modern Approach
Gap on parent
One property

How it works

The old pattern was margin on every child (e.g. margin-right: 16px) and then a :last-child rule to set margin to 0 so the last item didn't add extra space. Or you used negative margin on the container to absorb the last child's margin. Both are fiddly.

With display: flex or grid and gap: 16px, the browser adds space only between items. No child margins, no overrides. Works the same for rows and columns, and you can use row-gap and column-gap separately if needed.

New CSS drops.

Join 600+ readers who've survived clearfix hacks.

ESC