April 3, 2012

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 absolutely, 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;
 }

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!