css absolute position won't work with margin-left:auto margin-right: auto
Question by user1118019
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?
Answer by kmb385
An element with position absolute has been removed from its normal place within the DOM. It cannot be centered because it does not have an actual parent to calculate the margins and be centered within.
Position relative works because the element has a parent which can be used to calculate the margins.
This article gives a good overview of assigning margins to absolutely positioned elements: http://www.vision.to/articles/margins-and-absolute-positioning.php
This forum provides a good description of why it does not work:
http://www.justskins.com/forums/css-margins-and-absolute-82168.html
Answer by Starx
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;
}