A Simple CSS Trick to Vertically Align Text
by Bandicoot Marketing on | 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:
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:
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.
3 comments for “A Simple CSS Trick to Vertically Align Text”