Spacing between flexbox items

nice ass picture nice ass · May 2, 2014 · Viewed 77.5k times · Source

This is what I want:

flex with spacing

The closest I've got. Applying margin on flexbox items, then removing half of it from the first & last children.

The problem is that :first-child is not always the first visually, because I may alter the layout order (example).

Is there a way to take the visual order into account when applying the margin?

Answer

agrm picture agrm · May 2, 2014

You can try setting the same margin for all the boxes, and then revert this on the container:

So replace this:

.flex > * { margin: 0 10px; }    
.flex > :first-child { margin-left: 0; }
.flex > :last-child { margin-right: 0; }

.flex.vertical > :first-child { margin-top: 0; }
.flex.vertical > :last-child { margin-bottom: 0; }

With this:

.flex.vertical { margin: -20px 0 0 -20px; }
.flex > * { margin: 0 0 0 20px; }
.flex.vertical > * { margin: 20px 0 0 0; }