Vertical Align Text in a DIV Element Using CSS

By | December 4, 2013

In the course of your web design projects, you may come across a situation where you are required to show several lines of text inside a div element. You may also need these lines of text to be centered horizontally. For most of the part, using text-align:center inside the parent div willdo the trick. However, in some situations, you may need to have the text to have the text aligned vertically inside the div element.

There is a CSS attribute vertical-align:middle. The one point that confuses most people is that just setting a vertical-align:middle in a div for example does not vertical align the text inside.

Results in this:

css vertical align not working as expected

The reason is, by default, a div is display:block And the text is to flow from top to bottom filling available space in such an element. Read about different display types here
When you change the display type to table-cell, it works as expected:

 

Vertical centering a div in another div

This gets trickier when you want to vertical center another div. One commmon method is to use CSS negative margin.

  • We use absolute positioning to place the inner div at 50% of the parent div.

    div top 50%

  • Then we use negative margin to pull half the height of the inner div up.

    css vertical align negative margin

Those are the common cases where you would like vertical align to work the way you want it. The first thing to remember is that you need to understand the basic layout concepts to really make it work. See the reference section below for more info.

Download Sample code: css vertical align

More reading

Leave a Reply

Your email address will not be published. Required fields are marked *