Vertically Centering Text, With Flexbox
A very common challenge for website designers is creating effective vertical alignment with text, especially with responsive website design. In the past, before Flexbox was around, you’d have to use tables
or clever absolute positioning, both of which weren’t very good solutions.
Flexbox
Nowadays however, vertically aligning text is quite simple, thanks to Flexbox. If you have never worked with Flexbox before, it’s simpler than you think. Definitely check out my Flexbox tutorial and get up to speed quick.
Vertically Aligning Text
HTML
Let’s first start out by creating the basic HTML tags we’ll need. Be sure to include a container for the title, as we will need to utilize that with Flexbox and absolute positioning.
<div class="box"> <img src="http://placehold.it/500x500"> <div class="title"> <h1>Title</h1> </div> </div>
CSS
Now that we have all the required HTML tags, we can begin integrating Flexbox styling.
* img{ max-width:100%; height:auto; } img{ display:block; } .box{ background:blue; max-width:500px; text-align:center; position:relative; } .title{ position:absolute; top:0; left:0; width:100%; height:100%; display:flex; flex-direction:column; justify-content:center; }
Live Example
See the Pen Vertically Centered Text with Flexbox by Richard (@barkins) on CodePen.
Wrap Up
Just keep in mind how Flexbox works with the parent child relationship. With that understanding, you’ll be able to easily create dynamic layouts, especially for responsive websites.