Here are two ways to vertically center a block-level element using CSS. The first method uses CSS flexbox, while the second method uses CSS transform.
Working on the one-page brochure site for my free WordPress starter theme, I wanted to keep the content simple and then center it vertically on the page. Here are two techniques for making it happen.
For the sake of this tutorial, here is the HTML that we’ll be using:
<div class="child">Diam non pellentesque maximus.</div>
So basically any parent block-level element that contains a child block-level element. You can use inline elements instead if setting them as
block via CSS.
CSS Vertical Center: Method 1
This technique uses flexbox to vertically center the child within the parent:
Browser support for flexbox is pretty good, but IE still having some problems (surprise surprise).
FWIW, this is the technique I ended up using for shapeSpace.io. I think the simplicity of flexbox is worth the trade-off of non-support in IE, which will display the content at the top of the page instead of centered. No big deal ;)
CSS Vertical Center: Method 2:
This technique for vertical centering works a bit different, using
transform on an absolutely positioned child element.
top: 50%; width: 100%;
Here we relatively position the parent element, and then absolutely position the child element. We then move the top of the child element 50% down, and then apply
transform to translate the element back up by half its width (i.e.,
-50%). Support for
transform enjoys solid support in all modern browsers, even good ol’ IE.
To horizontally center the child element using the above technique, change the width to something less than
100%, and then add an auto-margin property, like so:
top: 50%; width: 50%;
margin: 0 auto;
For way more in-depth guide to centering in CSS, check out my friend Chris Coyier’s post, Complete Guide to Centering in CSS.
Like our new Facebook Page to show support!