Vertical centering with CSS
Friday, Nov 16, 2007
A common question among those who are new to CSS and are just getting off table-based layouts is "How do i vertically align an element?" With tables it's very easy: you simply go vertical-align: middle; and everything in the table-cell will be vertically aligned.
“With a little CSS trickery you can vertically align any element that has a fixed width and height.”
No other element can vertically align other elements inside it except the table-cell. But with a little CSS trickery you can vertically align any element that has a fixed width and height.
If it wasn't for IE (as usual) you could use the display: table-cell; and display: table-row; properties to allow real vertical alignment in any element, but as usual you're just going to have to wait for IE to catch up.
The way it works is that you position the element absolutely, setting both its left and top properties to 50%. This way the element's top left corner will be in the exact middle. What you then need to do is use negative margin to pull the element towards the top-left corner in order to center it. The negative margin needs to be exactly half of the element's width and height. As usual when dealing with widths and heights and the box-model you also have to compensate for any border or padding the element might have.
Here's the relatively simple code:
As you can see the top margin is exactly half of the height and the left margin is exactly half of the width.