I checked MDN to see what means to have an auto value for margin property and it says: "auto is replaced by some suitable value, e.g. it can be used for centering of blocks."
But what it is that suitable value, and suitable for what?
I tried myself some experiments and I saw that if I add margin-left: auto, the container goes to right (like is floating to right):
#container { background: red; width: 120px; margin-left: auto; }
http://jsfiddle.net/sph2j6jx/
Does it mean that adding margin auto is actually something like "take all the space available"? And when you add both left and right margins it centers the div because it tries to take all the space from left and from right?
So in margin: 0 auto, the top/bottom margin is 0, and the left/right margin is auto, Where auto means that the left and right margin are automatically set by the browser based on the container, to make element centered.
margin-top: length|auto|initial|inherit; Property values: length: It is used to specify the length of margin with a fixed value. This value can be positive, negative or zero.
The percentage is based on the width of the container. margin-left: auto; The auto keyword will give the left side a share of the remaining space. When combined with margin-right: auto , it will center the element, if a fixed width is defined.
margin-right: auto; The auto keyword will give the right side a share of the remaining space. When combined with margin-left: auto , it will center the element, if a fixed width is defined. First item.
Auto margins
Depending upon the circumstances, provision of an auto value instructs the browser to render a margin according to the value provided in its own stylesheet. However, when such a margin is applied to an element with a meaningful width, an auto margin instead causes all of the available space to be rendered as whitespace.
From w3.org
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