Centering Text Vertically

From CSS Discuss

Jump to: navigation, search

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.

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! (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. ( see discussion)

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.

Personal tools