Vertically centering text using CSS

Filed under: CSS Stylesheets

As many people have discovered, there is no CSS definition for vertically centering text in a block element such as a div. One can achieve this in HTML and XHTML, by using a table and the attribute “valign=middle” to vertically center text, however when you want to achieve the same thing in CSS, that’s when it gets quite tricky.

There are a couple work arounds for this problem. Both these work arounds only work for ONE line of text, the solution for multiple lines of text will be posted soon.

  1. Use vertical-align and an invisible image
  2. Use line-height

1. Use vertical-align and an invisible image

Horizontal centering with CSS has been around for a while and can be easily achieved by using “text-align:center”. The closest definition for vertical alignment in CSS is “vertical-align” which may be top, middle or bottom.

vertical-align:top
vertical-align:middle
vertical-align:bottom

The problem with vertical-align is that it’s an inline style, so it won’t vertically center your text in a div when used by itself. For example:

<div style="width:25em; height:10em; border:1px solid #CECECE; vertical-align:middle">
This text should be vertically centered, but it's not.
</div>

This text should be vertically centered, but it’s not.

To use “vertical-align:middle” to center your text, you will need to put an image of the same height as your block element next to the text you want vertically centered. For example:

<div style="width:25em; height:10em; border:1px solid #CECECE">
<img src="/sg/t.gif" alt="" style="width:1px; height:10em; vertical-align:middle" />This text is vertically centered.
</div>
*

This text is vertically centered.

* t.gif is a transparent gif of 1 x 1 pixel.

2. Use line-height

To use line-height to vertically center text, specify the line-height to be the same height as the block element. For example:

<div style="border:1px solid #CECECE; width:25em; height:10em; line-height:10em">
One line of vertically centered text.
</div>

One line of vertically centered text.
divider

Leave a Comment