Designers often want to have an image or even the entire page dead-centered vertically and horizontally within the viewport (the area the browser uses to render a page). This is easy using tables and the height attribute (which although has widespread support, has never been in any HTML specification).
There are two solutions to this, the best CSS2 way and the works-in-IE way…
Solution 1: The Official CSS2 Way
Although it wasn’t a part of the original CSS2 specs, in the errata it states you can set margins to auto on an absolutely positioned element to center it, like this:
.centered {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 50%;
height: 50%;
margin: auto;
background-color: red;
color: white;
}
(try it in your browser)
…which should then result in <div class=“centered”>bleh</div> being positioned right in the middle of the viewport. It works fine in Gecko and Opera 7, but sadly not in IE/win.
Solution 2: The “It (sort-of) Works in IE” Way
This is hackish, apparently renders nothing at all on IE/mac, and makes the content goes off the edge of the screen if the browser window is too small. Not that ideal then…
.centered {
position: absolute;
top: 50%;
left: 50%;
margin-top: -25%;
margin-left: -25%;
background-color: red;
color: white;
}
That’s the best I’ve seen, I’m afraid. Maybe one day I’ll try combining the two solutions (maybe with some script?) and coming up with something that works much better, but for the moment, that’s your lot.