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?
if the absolute element has a width,you can use the code below
Working JSFiddle below. When using position absolute,
margin: 0 auto
will not work, but you can do like this (will also scale):Update: Working JSFiddle
I already had this same issue and I've got the solution writing a container (.divtagABS-container, in your case) absolutely positioned and then relatively positioning the content inside it (.divtagABS, in your case).
Done! The margin-left and margin-right AUTO for your .divtagABS will now work.
When you are defining styles for division which is positioned
absolute
ly, they specifying margins are useless. Because they are no longer inside the regular DOM tree.You can use float to do the trick.
If the element is position absolutely, then it isn't relative, or in reference to any object - including the page itself. So
margin: auto;
can't decide where the middle is.Its waiting to be told explicitly, using
left
andtop
where to position itself.You can still center it programatically, using javascript or somesuch.
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.