I’m using CSS as follows:
.center
{
width: 30%;
position: absolute;
margin-left: auto;
margin-right: auto;
display: block;
height: 100%;
text-decoration: none;
overflow: hidden;
right:0;
left:0;
}
It doesn’t work without the
right:0;
left:0;
(I found that solution in a comment here)
Why?
Okay, so bear with me… this whole thing has to do with the Visual formatting model, in particular with the way in which widths and margins are calculated.
There are several things that need to be taken into account, like
displayandposition(which can all be seen on section 10.3 of the CSS spec).For your case in particular we are talking about absolutely positioned non-replaced elements (since it is not an image or anything with intrinsic size), so it’s section 10.3.7 Absolutely positioned, non-replaced elements.
According to your css, you have a defined width, so not
auto, and both your left and right margins areauto. So it boils down to what are the left/right values:If left/right are defined, so not auto, the following rule applies:
If left/right are not defined, so they default to auto, the following rules apply:
First:
Second:
So you can see that if you do not define a specific value for left/right, your margins actually become
0and you end up having the div either to the left or to the right of the container depending on the value of thedirectionproperty (you can test this by putting something likehtml { direction:rtl; }on your css, the div should go to the right instead of the left when left/right are auto)However if you do specify the values, in your case 0, the “two margins get equal values” effectively centers the elemement.
Hope it helps!