Its seems that for all its amazing uses, and the huge supporting community behind it, certain very easy topics seem to be holding back the full power of css from the newer css adopters. Vertically and horizontally centering an element seems as if it should be very straight forward right? Wrong. Despite my years of CSS coding, I’ve never found an article or even a discussion of how to vertically and horizontally center an element consistently, and after hours of searching my frustrations were such that I decided to put some time into discovering the solution myself (shock horror!!).
It turns out that the actual solution is very easy and even the most elementary of browsers (say the IE’s of the world) understand it. All 100% standard to boot. Before going on though, the solution does work for a specific situation:
- You must know the width and height of the element your trying to vertically center
- You must have a larger box to contain it in (most of the time this can even be just the body).
Ok so lets look at some code. We need to start with a div and define its width and height:
#center_me {
width: 500px;
height: 350px;
}
Now lets add some positioning information:
#center_me {
width: 500px;
height: 350px;
top: 50%;
left: 50%;
}
That should be it right? Again wrong.
That will place the top left edge of our box ‘center_me’ right in the middle of the space, which is not what we want. So we now want to play with our margins so that it positions the box right where its needed. We achieve this with negative margins:
#center_me {
width: 500px;
height: 350px;
top: 50%;
left: 50%;
margin-top: -175px;
margin-left: -250px;
}
Why -175 and -250 respectively? Well in order to align the ‘center_me’ div so that its center most point is right in the middle of the box we’ve defined, we need to move the top left corner half the height of the box (margin-top: -175px) and half the width of the box (margin-left: -250px).
Your box is now right in the middle of what ever element you want. It maybe an easy solution but I hope it can help some of you out there who were struggling to solve what is a very easy but common problem.

October 15th, 2007 at 12:18 pm
Hmmmm… I dont really get it.. Instead of using CSS, why dont you just make a single bitmap image instead….
Why bother with this overkill method?
October 15th, 2007 at 7:05 pm
Hi Dave, thanks for the comment.
I’m not sure if I understand your method of “a single bitmap image”. Of course there are always a number of ways to do anything, but I like this solution since it has practical applications to exactly center a div when the dimension of the container is known. It also allows for the code to adhere more strictly to xhtml and css standards, not to mention space reduction for load times when an image isn’t needed for positioning.
Cheers Ben