matt matt - 1 year ago 53
CSS Question

margin 0 auto centers an element, why doesn't margin 1 auto do the same?

I understand that

margin: 0 auto;
means a margin of size 0 on the top and bottom of the element, and a margin of size whatever is available, divided equally, on the left and right of the element.

This works as I would expect in the following example - but when I change it to
margin: 1 auto
(or any other number) the inner element moves all they way over to the left. I would have expected it to remain centered but to have shrunk vertically.


#outer {
height: 30px;
background: blue;
#inner {
margin: 0 auto;
width: 100px;
height: 100%;
background: red;

<div id="outer">
<div id="inner"></div>

Answer Source

The reason your code fails when you change it to margin: 1 auto is that 1 is not a valid CSS measurement.

Only 0 can be written without a unit (such as px or pt). If you change it to margin: 1px auto, it works as expected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download