36

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?

Alin Ciocan
  • 3,082
  • 4
  • 34
  • 47

2 Answers2

22

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

emmanuel
  • 9,607
  • 10
  • 25
  • 38
  • 1
    "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." Hmm, sounds unlikely to me. Would be interesting to what circumstances the author had in mind. – Alohci Oct 07 '14 at 08:26
  • 7
    What does it mean by meaningful width? – Gwater17 Aug 09 '17 at 22:50
  • 1
    @Gwater17 By meaningful width, this generally means explicit width. I agree the docs could be better – alaboudi Aug 21 '21 at 23:16
5
#main {
  width: 600px;
  margin: 0 auto; 
}

<div id="main"> Setting the width of a block-level element will prevent it from stretching out to the edges of its container to the left and right. Then, you can set the left and right margins to auto to horizontally center that element within its container. The element will take up the width you specify, then the remaining space will be split evenly between the two margins.</div>

Deepak Biswal
  • 4,280
  • 2
  • 20
  • 37