View Single Post
Old 07-10-2007, 08:00 AM  
StuartD
Sofa King Band
 
StuartD's Avatar
 
Join Date: Jul 2002
Location: Outside the box
Posts: 29,903
Another tip that took me a while to figure out.....

4. Centering a div that has absolute positioning

If you've ever set something to absolute, then tried to put margin: auto on it... you'll be thinking "why does it work in one browser, but not the other one if doctype is set to strict?"

There is a trick to this that will work in all browsers...

First you take the width of the div. In my example, we'll go with 500px;

So we have
#div {
width: 500px;
}

Now we need it to be in the middle... so we apply a "left: 50%;"

#div {
width: 500px;
left: 50%;
}

That puts the left edge of the div in the middle. Which is close, but not right because the center of the div should be in the center of the page.
To solve this, we margin it back by half. Half of 500px is 250px;

#div {
width: 500px;
left: 50%;
margin: 0px 0px 0px -250px;
}

And presto, your absolute positioned div is now dead center in the page.

It's also right at the top edge. Centering it vertically is a whole other beast and will require some javascript, especially if you scroll. And this is a CSS thread, not a javascript thread. Sorry, but it is possible.... keep working and you'll get it.
StuartD is offline   Share thread on Digg Share thread on Twitter Share thread on Reddit Share thread on Facebook Reply With Quote