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?
All answers were just a suggested solutions or workarounds. But still don't get answer to the question: why margin:auto works with position:relative but does not with position:absolute.
Following explanation was helpful for me:
"Margins make little sense on absolutely positioned elements since such elements are removed from the normal flow, thus they cannot push away any other elements on the page. Using margins like this can only affect the placement of the element to which the margin is applied, not any other element." http://www.justskins.com/forums/css-margins-and-absolute-82168.html
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 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
and top
where to position itself.
You can still center it programatically, using javascript or somesuch.
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.
.divtagABS {
float: left;
margin-left: auto;
margin-right:auto;
}
if the absolute element has a width,you can use the code below
.divtagABS{
width:300px;
positon:absolute;
left:0;
right:0;
margin:0 auto;
}
Working JSFiddle below.
When using position absolute, margin: 0 auto
will not work, but you can do like this (will also scale):
left: 50%;
transform: translateX(-50%);
Update: Working JSFiddle
Source: Stackoverflow.com