How to Center a Div

Apr10
Missing Image
By SiteCrafting Staff

Centering a div horizontally and vertically has always been a pain for CSS. Not any more! With this trick, you can create a centered block in no time.



During my morning blog reading I happened upon a blog post by Matt Taylor on a nice way to horizontally center menus. While centering menus isn't a common design element, centering a box a window is. In fact, this is a very difficult problem for front end developers. I, myself, tend to give up and use a JavaScript hack to get it all centered up.

But after reading Matt's post, I discovered you can use his method vertically as well. I have uploaded a demo so you can see it in action.

The core of this method is that a wrapper is 50% of the body to the right, and the container is 50% of the wrapper to the left. Assuming the wrapper and the container are the same size,  this will result in a centered block. The CSS looks like this:

#wrapper, #container {
height: 500px;
width: 600px;
}
#wrapper {
bottom: 50%;
right: 50%;
position:
absolute;
}
#container {
left: 50%;
position: relative;
top: 50%;
}

From my testing, this works in IE 6 and 8, Firefox 3, Safari 3 and 4 and Opera 9. If you have tested it in anything else, post about it here.

Demo

Update: (04/12/2009)

After a bit more testing, it looks like the technique also works in IE7. Also, because the container will be the size of the wrapper, you only need to set the height and width of the wrapper. Also, you can even set the position of the wrapper to absolute in IE6 and fixed in everything else to get a nice "centered on scroll" effect that falls back to centered at the top for those who don't support it. Furthermore, if IE6 isn't a concern, setting a max-height: 100% and max-width: 100% to the wrapper will make sure that the box isn't centered when the window is smaller then the container. This will give a nice effect for small screens. The change would look like this:

#wrapper {
position: absolute;
bottom: 50%;
right: 50%;
height: 500px;
width: 600px;
}
#container {
position: relative;
left: 50%;
top: 50%;
}

If this post was helpful to you please help pass the word by liking it, thanks all!

Dev

Back To Feed