June 21, 2006

css vertical positioning

Filed under: useful snippets — yordan @ 10:08 am


Vertical centering is just as important. I want to be able to (without tables) place a 500×500 box center of the window without resorting to some wierd javascript to do it. You give me a div (or p) that does this in all browsers with zero javascript and I will be impressed.

The way I usually do it is with negative margins. It's kind of a workaround, but it does work. Position the div 50% from the top and left, and then give it a negative margin-top & margin-left equal to 1/2 its own height & width respectively (in the case of 500×500, use a -250px margin) and it should center vertically.

For example, I use something like this on one of my sites:
#container {
position: absolute;
left: 50%;
top: 50%;
width: 500px;
height: 500px;
margin-left: -250px;
margin-top: -250px;


Create a free website or blog at

%d bloggers like this: