Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

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.

Code:

#outer {
  height: 30px;
  background: blue;
}
#inner {
  margin: 0 auto;
  width: 100px;
  height: 100%;
  background: red;
}
<div id="outer">
  <div id="inner"></div>
</div>
like image 635
matt Avatar asked Mar 18 '23 21:03

matt


1 Answers

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.

like image 145
Chris Middleton Avatar answered Mar 26 '23 01:03

Chris Middleton