Say you have the following CSS applied to a div tag
.divtagABS {
position: absolute;
margin-left: auto;
margin-right: auto;
}
the margin-left and margin-right does not take effect
but if you have relative, it works fine
i.e.
.divtagREL {
position: relative;
margin-left: auto;
margin-right: auto;
}
Why is that? I just want to center an element.
Can someone explain why setting margins to auto in absolute position does not work?
EDIT : this answer used to claim that it isn’t possible to center an absolutely positioned element with
margin: auto;, but this simply isn’t true. Because this is the most up-voted and accepted answer, I guessed I’d just change it to be correct.When you apply the following CSS to an element
And then give the element a fixed width and height, such as 200px or 40%, the element will center itself.
Here’s a Fiddle that demonstrates the effect.