Go Back to Dynamic Site Solutions :: CSS

Vertically Centering With Line-Height

In the examples the left elements has its line-height set to its height; the right elements have the normal line-height. For example 2 the image (<img>) in the left element also have vertical-align:middle. Example 4 shows that this technique does not work if there is more than one line box in the element.

Example 1 works in IE5+/Win, Firefox, Netscape 6+, Opera 6+, Safari, Konqueror 3, and IE5/Mac. Example 2 works in Firefox, Netscape 6+, Opera 7.5+, Safari, Konqueror 3, and IE5/Mac but not in IE/Win. Example 3 is the same as example 2 except it has a few extra rules in the stylesheet that is in the conditional comment that makes it work in IE5+/Win.

There's one other thing I should mention. This technique doesn't work to vertically center inline, replaced elements, e.g. <img>s, when a browser is in Almost Standards Mode, which is triggered by a complete, Transitional DOCTYPE. There is an alternative, however. You can give the parent of the <img> display:table-cell and vertical-align: middle. This is shown in Example 5. (IE5-7 do not support display:table-cell, nor do they have an Almost Standards Mode, so you still need the workaround for them.) There is another issue you might run into. An element with display:table-cell in a browser that supports display:table-cell can't be floated.

Demonstration

Example 1 (one line of text)

Example 1
Example 1

Example 2 (an image)

example image
example image

Example 3 (an image with IE5+/Win fix)

example image
example image

Example 4 (two lines of text)

Example 4
Example 4
Example 4
Example 4

Example 5 (see description above)

example image
example image

Related Links:

Last update: 2009-03-18