How to Align Text Vertically with CSS

CSS Selectors to Customize Your Site's Design

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:

1

Author

  • Valentin Garcia

    Valentin discovered Joomla in 2010, and since then he has considered it as the best CMS. Valentin has been coding extensions and templates for Joomla for many years and truly enjoys helping people build their own websites with Open Source tools. He lives in San Julián, Jalisco, México.

0 0 votes
Article Rating
Subscribe
Notify of
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Ivan Milincic
Ivan Milincic
7 years ago

Or just use a flexbox 🙂

Olcay Ergul
Olcay Ergul
5 years ago
Reply to  Ivan Milincic

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.

2
0
Would love your thoughts, please comment.x
()
x