Flexbox will get you 99% of the way there, until you open it in IE…
Often when I’m building a page header, I want the header to be at least a certain height and I want the content to be centered vertically within it. In the past, we would come up with some messy solution, usually involving extra vertically aligned inline-block elements to handle this, but with the advent of flexbox, we can now make this happen in a much cleaner manner:
.page-header { display: flex; background-color: #ccc; min-height: 200px; align-items: center; justify-content: center; text-align: center; border: 2px solid red; } .content { border: 2px solid green; }
And in most browsers, this will produce something that looks like the following:
But in Internet Explorer (of course…), the content block will not appear vertically centered:
Rats!! Turns out this is a bug in Internet Explorer, which is elegantly explained here by GitHub user philipwalton (https://github.com/philipwalton/flexbugs#flexbug-3):
In order for flex items to size and position themselves, they need to know how big their containers are. For example, if a flex item is supposed to be vertically centered, it needs to know how tall its parent is. The same is true when flex items are told to grow to fill the remaining empty space.
In IE 10-11,
min-height
declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.
Luckily he also goes on to provide a workaround:
For cases where
min-height
is required, the workaround is to add a wrapper element around the flex container that is itself a flex container in the column direction. For some reason nested flex containers are not affected by this bug.
In our example, I didn’t want to add a wrapper outside .page-header
, so I’ve nested another div called .wrapper
between .page-header
and .content
, moved my flexbox centering CSS into .wrapper
, and added display: flex;
and flex-direction: column;
to .page-header
:
.page-header { display: flex; flex-direction: column; background-color: #ccc; border: 2px solid red; } .wrapper { display: flex; min-height: 200px; align-items: center; justify-content: center; text-align: center; border: 2px solid yellow; } .content { border: 2px solid green; }
And boom! We’ve got a page header that’s centered on all our browsers!
Let us know if you have any troubles implementing this on your own website. We’re here to help! Or maybe you have a nicer solution, we’d love to hear it!