user1118019 user1118019 - 1 year ago 100
CSS Question

css absolute position won't work with margin-left:auto margin-right: auto

Say you have the following css applied to a div tag

.divtagABS {
position: absolute;
margin-left: auto;

the margin-left and margin-right does not take effect

but if you have relative, it works fine

,divtagREL {
position: relative;
margin-left: 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?

Answer Source

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

position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download