View Full Version : css positioning and negative margins
php_brian
10-10-2003, 02:46 AM
ok, im trying to figure out the best way of centering a div box horizationally. here's the code a friend gave me to do that with a 650px box. but i need it to center a 804px box. how did he figure out the margin-left number?
div#body {
position: absolute;
margin-left: -326px;
left: 50%;
top: 15px;
width: 650px;
}
my source:
http://bluerobot.com/web/css/center2.html
Centering: Negative Margin
The box's left edge is positioned at the horizontal center of the page using "position:absolute; left:50%;". Then, the box's left margin is set to the opposite of half the box's width using "margin-left:-266px;".
body {margin:0px; padding:0px;}
#Content {
position:absolute;
left:50%;
width:500px;
margin-top:50px;
margin-left:-266px;
padding:15px;
border:1px dashed #333;
background-color:#eee;
}
:D
php_brian
10-10-2003, 02:11 PM
i'm getting lost when it says:
Then, the box's left margin is set to the opposite of half the box's width using "margin-left: -266px;".
:(
ok.. in the example i posted...
the box is 500px wide.
the left is set at 50% so that centers. then we want to move the left margin back (to the left more than it is) so we add the negative margin.
in order to figure the negative number (and you may have to play with the numbers to get it exactly where you want) you add the 500 px plus padding of 15 px on each side (left and right) PLUS the 1 px border on the left and right as well (because all of it takes space). so that gives you 532. 532/2 (50%) is 266. we want to shove left-margin of the box to the left on the screen so we set it as a
-266.
in your case (and i tested it).. since you just want a box 804 wide.. divide in half and put that as the negative number. change the width and the margin-left in your friends example and it should work.
such as this:
div#body {
position: absolute;
margin-left: -402px;
left: 50%;
top: 15px;
width: 804px;
}
you can make it more complicated by adding borders, padding, etc as seen with the example i posted from bluerobot, but you don't have.
it's pretty cool. like i said.. play around with it. leave out the margin left to begin with to see where it puts the box (helps if you have a border and background color to be able to see it on the screen. ha ha) then add the negative number back to see how it adjusts it.
i don't know what level you are at with CSS, but i have found that the more you play with each attribute the easier it is to see how it all falls into place.
again, let me know if i just didn't make sense at all.
php_brian
10-10-2003, 03:33 PM
ok thank you very much. i understand now :D
no problem. any other ques.. let me know.
vBulletin® v3.7.0, Copyright ©2000-2009, Jelsoft Enterprises Ltd.