How to Align Text Vertically with CSS
One of the big challenges in web design involves aligning text vertically.
This is easy to achieve by using tables, however using tables to design a layout is not recommended.
In this tutorial, I’ll share with you how to align text vertically with CSS. Let’s start…
The HTML
We need two divs, one of them is the container and the other wraps the text:
<div id="container">
<div class="content">
Your text goes here
</div>
</div>
Replace the dummy text with your own.
The CSS
The CSS will point to the two elements from the previous step:
#container {
display: table;
height: 400px;
margin: 0 auto;
width: 400px;
}
.content {
background: #f2f2f2;
padding: 40px;
text-align: center;
display: table-cell;
vertical-align: middle;
}
As you can see, we use properties to “emulate” a table. We use display: table for the container, and display: table-cell, plus also vertical-align: middle for the text wrapper.
Optional: you can customize the values for these properties:
- background
- padding
- text-align
The end result
Preview the result to see the text is perfectly centered vertically:
Or just use a flexbox 🙂
The flex property may be good choice on the modern browsers. But if you are developing a cross browser compatible website then using the flex property will raise compability issues. The flex property especially should not be used if you are considering IE8, IE9, IE10 compability.