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.

Old 6 lines
1.grid {
2  display: flex;
3}
4
5.grid > * {
6  margin-right: 16px;
7}
8.grid > *:last-child { margin-right: 0; }
Modern
3 lines
1.grid {
2  display: flex;
3  gap: 16px;
4}

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.

Browser Support
97%
Chrome Firefox Safari Edge
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.

ESC