Aug
05
2010

A Simple CSS Trick to Vertically Align Text

by   |  Posted in Tutorials  |  3 comments

I was trying to vertically align text within a div container and it just wasn’t working for me. You would think that using vertical-align in your CSS would accomplish just that, but you would be wrong. I found a way to do it using three div containers and absolute positioning but I felt that was a little overkill for my purposes.

This was the box I was designing:

Some Text

After doing a lot of digging around, I discovered that you could set the line-height of your text to be the same as the height of your div container and this is what you would get:

Some Text

That did it.

Here is the CSS I used:

div.container {
  width: 100px;
  height: 100px;
  background: #666;
  color: #fff;
  text-align: center;
  line-height: 100px; /* where the magic happens */
}

The only way this technique wouldn’t work for you was if you had text on two lines, then the second line would be 100 pixels below the first. Hmm… maybe I could figure out a solution to that one as well.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , , , , , , , , , , ,

Short URL: http://bit.ly/dkLPTb

Discussion 3 Comments

  1. VDigital on August 6, 2010 at 2:02 am

    Replace your line-height by

    display:table-cell;
    vertical-align:middle;

    • Kevin Lloyd on August 12, 2010 at 4:59 pm

      Unless you want your alignment to work in IE5, 6 or 7.

  2. Morten Kaltoft on August 7, 2010 at 11:56 am

    Not really a trick. I use it all the time ;-)