Flex justify content equally distanced items

I want to share a hack (or a trick if you prefer) my colleague Marko showed me today.

What is the problem? We want our flex items to be equally distanced between each other and from the parent's edge. Unforunately space-evenly (I wasn't aware of this property, thanks Marc for mentioning it in the comment below.) is not supported in IE and Edge. And space-around or space-between won't work.

You can see what we are trying to achieve in the first row, and how the latter two are behaving.

Flex justify content examples

Trick is really simple, use space-between and add empty pseudo elements (::before and ::after) to the parent element. Pseudo elements have no width, but they are still "pushing" real elements from themselves.

.wrapper {
  display: flex;
  justify-content: space-between;
}

.wrapper::before,
.wrapper::after {
  content: '';
}

This hack works with dynamic number of elements, dynamic widths and for any flex direction.

You can see it in the action below:

Comments (1)

Marc Bernstein
07. Sep 2018, 13:42

This is a useful trick for when you need to support browsers until space-evenly is more widely supported.