2

I was searching the archives and came across the following article about how to center a div within a div, where the solution was to apply the following styles to the inner div:

#inner {
    width: 50%;
    margin: auto;
}

The answer states that the margin:auto is what causes the centering. How exactly does this work?

Community
  • 1
  • 1
geekchic
  • 1,526
  • 1
  • 11
  • 21

2 Answers2

1

margin:auto; is specifically designed to automatically set a margin, usually for the purpose of centering an element. It actually only works on the left and right margins. Using margin:auto; is shorthand for the following:

{ margin:0px auto 0px auto; }

And to spell that out further:

{ margin-top:0px; margin-right:auto; margin-bottom:0px; margin-left:auto; }

Check out the CSS2 spec.

Stephen
  • 18,827
  • 9
  • 60
  • 98
0

It basically solves the equation margin = ("outer-width" - "inner-width") / 2 and sets the result to the margin value.

The result is, that the margin of your inner div is the same on both sides and its overall width (width + 2×border + 2×margin) fills exactly your outer div. So it's body is centered.

Simon
  • 4,395
  • 8
  • 33
  • 50