07 Sep 2018

This article will take about 1 minute to read.
1 Comment

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 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:

Category
CSS/SASS

Comments (1)

Marc Bernstein
07 Sep 2018, 01:42 PM

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

Leave a comment

Sending failed, please try again.
Thank you! Your comment is sent. Please note that all of the comments go through moderation.