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?
"An element with position absolute cannot be centered..." Actually, this is not true: The key is to set all top/bottom/left/right properties to 0 and declare width and height , then margin: auto will automatically center the absolutely positioned element.
margin:auto won't work when you have a float or haven't specified a width. kohoutek: margin:auto won't work when you have a float or haven't specified a width.
First things first, each of the elements above are blocks and have set margin: 0 auto, but it does not work since blocks have width equal to 100% by default (the first example). The block covers the whole page and therefore cannot be centered.
By assigning auto to the left and right margins of an element, they take up the available horizontal space in the element's container equally – and thus the element gets centered.
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.
I've used this trick to center an absolutely positioned element. Though, you have to know the element's width
.
.divtagABS { width: 100px; position: absolute; left: 50%; margin-left: -50px; }
Basically, you use left: 50%
, then back it out half of it's width
with a negative margin
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With