WvGdZL by Myri (@mynimi) on CodePen.
As you can see in the example above the problem becomes obvious. The examples float1 and flex1 are written how I’d normally tackle this problem, because it’s fast and easy. But if we increment the length of one of the sides you can see that the middle element is not really centered.
Before the middle element is centered, the width will be reduced on both sides and the element is centered within the space that’s left.
In flexbox this is called space-between
. The space between each of the elements is the same. It may be really helpful in some placed, but for this layout the second examples are what we want.
Okay, for version 1 we need a very basic markup. A container and three subcontainers with the contents
Then we’ll add our CSS (I’m using Autoprefixer to take care of prefixing, so no prefixes in my CSS). Who wants to see the Sass is very welcome to go look at the CodePen.
Basically we style the container
Then for the float-version which I know a lot of people still would use first.
Alternatively the solution is flexbox is much shorter and less probable to break something else. So that’s the solution I will go for. With a Sass mixin this step only takes me 3 lines.
So you can see that this version breaks. To stabilise it, I had a pretty simple idea.
The idea is to take containers of the same size. If all of the elements are the same width, you can align the content within easily. The inner markup needs a little bit of an adjustments then.
And in CSS it looks like that:
float
flexbox
And that’s it. And the centering looks balanced.