Footnote

by Joe Gillespie — Jan 1, 2003

Vertical Centering with CSS

Although it is easy to centre elements horizontally in a CSS box, there is no direct equivalent of the 'valign' used for vertical alignment inside table cells – but there is a way to spoof it.

When you think of absolute positioning, you probably think in terms of absolute pixels, but absolute positioning also works with percentages. For instance, if I have a box that is 250px wide by 70px high, I could position it at absolute 50% from the top and 50% from the left of the page and its top left corner would be at the centre of the browser window.

If I then give it negative left and top margins that are exactly half of its width and height, the box is put back smack bang in the middle of the window, no matter what size it is.

Although this works fine in Explorer and Netscape 7/Mozilla, Opera prefers to do its own thing and doesn't play ball. It centres horizontally okay, but the contents of the box are placed incorrectly vertically. Here is a workaround that works in all (recent) browsers.

It requires an extra box, 'horizon', which is given a nominal height of 1px so it becomes a thin horizontal line and its overflow property is set to 'visible' so that its contents aren't cropped. This box centres vertically on the screen just fine.

The 'content' box is then put within that vertically centred 'line' but instead of using the negative margin value, which fools Opera, it is given a negative top position of half the 'content' box height and Opera seems quite happy with that.

Note: Jan 1, 2004. Opera no longer requires this workaround. If you are having problems with this technique, check your DOCTYPE. HTML 4.01 Transitional usually works fine but using Strict or XHTML can cause problems, especially with IE.

Del.icio.us Digg Technorati Blinklist Furl reddit Design Float