Jump to content

Flex justify content equally distanced items

Posted in CSS/SASS · 1 minute read

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-evenlyI wasn't aware of this property, thank you 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)

7. September 2018
Marc Bernstein

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