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;  
    margin-right: 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;  
    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

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.

Answered By – Kevin Bowersox

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.