What does margin auto mean?

Alin Ciocan picture Alin Ciocan · Oct 7, 2014 · Viewed 13.7k times · Source

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?

Answer

emmanuel picture emmanuel · Oct 7, 2014

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