Vertically centering one line of text

Vertically aligning with tables was a doddle. To make cell content line up in the middle of a cell you would use vertical-align: middle. This doesn't really work with a CSS layout. Say you have a navigation menu item whose height is assigned 2em and you insert this vertical align command into the CSS rule. It basically won't make a difference and the text will be pushed to the top of the box.[deleted spam link]

Hmmm... not the desired effect. The solution? Specify the line height to be the same as the height of the box itself in the CSS. In this instance, the box is 2em high, so we would insert line-height: 2em into the CSS rule and the text now floats in the middle of the box - perfect![deleted spam link] [deleted spam link]

(taken directly from [Evolt's 10 CSS tricks you may not know])

Tantek has one small addition to this tip:

[Ten CSS tricks ¡ª corrected and improved]

"The only bit I might add is that due to the metrics of the specific font, the text may or may not appear precisely centered. As a result, you may need to nudge the text up or down a bit with a specific 'vertical-align' absolute length value."

Also some good points, additions, and corrections to the original evolt article. Good reading.

  • Mark, care to explain? I'd be interested in hearing more on this. - Jack
  • consider lynx/links and other text browsers. The original table layout might work with them. The new CSS hack probably won't. It is often the case that going from table layout to pure CSS layout one loses some device independence.[deleted spam link] -Mark
  • surely text browsers would not render a table based layout well at all; with CSS at least we can present a semantically correct document instead. - Leszek
  • IMHO, much less abuse of CSS than, for example, playing with position: relative, top: 50% and negative margins - Leszek
  • That is much more horrible, I agree (especially the negative margins horror) - Mark

Vertically centering a block of text

The line-height trick above will only work if the text you want to center is one line. If it is multiple lines, you need to use something like this [three-div solution] with combination of absolute position for Internet Explorer and display: table for other standard browsers. This will also work on non-text objects.

A similar method using less markup is described in [Centering Multiple Line Content with CSS].