Absolute center a div

In a recent experiment I tried to horizontally and vertically align a website. There are many ways to do that, but not all work in all the browsers or are XHTML strict valid and none of those solutions incorporated variable height.

In this tutorial I will show you how align a div element to the absolute middle with dynamic height. This is a great solution if you have a website with external sources such as data from databases, rss-feeds and so on.

The example works in Safari, Firefox, Chrome and IE8. Also an IE7 fix included in the source code.

Setting up the XHTML

To make the website stay in the center of the page, we need a total of three divs: container, centered and content as shown below.

Setting up the CSS

Now that we have the wrappers, it’s time to add the stylesheet.

First off is the div with an id of container, we would like to have it take up the full page and to display itself as a table.

Next is the centered div. To make sure we can position it correctly, we set the display to table-cell. If you want to include IE7, you need to set the position to absolute.
All we have to do now is to set the div 50% from the top and align it to the middle.

Last but not least is the content div. Because we want it to be also horizontally aligned to the middle, set the position to relative. That way we can take advantage of the right and left margins set to auto. Just don’t forget to put in the width of your website. The last thing to do is to set the top property to the value of -50%.

This entry was posted on Friday, March 19th, 2010 at 22:30and is filed under tutorials. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

Hi thanks a lot for a discerning post, I really found your blog by mistake while searching on Goole for something else closely related, in any case before i ramble on too much i would just like to say how much I loved your post, I have bookmarked your site and also taken your RSS feed, Once More thank you very much for the blog post keep up the good work.

In newer versions of HTML the “<center>” tag and the “align” property has been deprecated. This happened because of splitting up the mark-up (HTML) and style (CSS). This is very useful for developing and browsers. You have a lot more control over element using classes.

If you want to center something in CSS, use “text-align: center” and “margin: 0 auto”. That way you can be sure it is properly displayed in all major browsers.

It’s the best time to make some plans for the long run and it’s time to be happy. I’ve learn this submit and if I may I desire to counsel you few fascinating things or tips. Maybe you could write next articles referring to this article. I wish to learn more things about it!