Mar 19 2010

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.

<div id="container">
	<div id="centered">
		<div id="content">
			<!-- content goes here -->
		</div>
	</div>
</div>

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%.

#container
{
 	position: absolute;
 	display: table;
 	height: 100%;
  	width: 100%;
}
#centered
{
	#position: absolute; /* IE7 fix */
 	display: table-cell;
 	vertical-align: middle;
 	top: 50%;
}
#content
{
	position: relative;
 	top: -50%;
 	width: 800px;
 	margin-right: auto;
	margin-left: auto;
}

Bothered by the scrollbars?

When you want a clean look without scrollbars, you can set the overflow to hidden. This will hide the scrollbars, but if your site is too long, users won’t be able to scroll!

body
{
 	overflow: hidden;
}

View demo or download source code.