Vertical & Horizontal Center with CSS

Web Devs have been promised that vertical centering an element within the browser view port will be a part of CSS3. Until we see adoption by the browsers getting that perfectly centered element is still a pain.


Well, here's a little bit of code I use, I've tested it in FF, IE7 and Safari 4, on Windows. I'd appreciate your testing if you have a browser/OS combo not listed here.

So, the CSS is:

<style type="text/css">
html,body { margin:0; }
.position { width:100%; height:0; position:absolute; top:50%; overflow:visible;}
.content { width:20em; height:16em; display:block; margin: -8em auto 0 auto; text-align:left; border:4px solid #999; padding:1em; }
</style>

And the html:

<div class="position">
<div class="content">
<p>
<p>Your data, <strong>$data[name]</strong>, has been created.</p>
</div>
</div>

Notice we are only using two classes here. First with .position we make sure to absolutely position 50% from the top of the view port. We can set the height to 0 and overflow to visible.

Next, the .content, which will directly contain our centered content, is horizontally centered using margin-left and margin-right auto. We set the desired hight and width and then set margin-top to roughly 50% of the height. This pulls the vertical placement up above the .position layer, thus centering the block vertically.

Give it a try; let me know what you think.