Margin 0 auto - why do we not need the "px"

width: 200px;
margin: 0 auto;

This sets an element’s vertical (top and bottom) margin to 0, and then auto centers the element between the width of 200px.

What I find frustrating (only a little) is the inconsistency of not needing a ‘px’ after the 0

You can add it if you want, but 0 pixels is the same size as 0 (anything).

CSS has many units of measurement, each of which being either an absolute length unit or relative length unit. They’re all weird and wonderful in their own ways, but they also all follow basic mathematic rules. The biggest one of these, of course, is: (anything) * 0 = 0.

In this case, you can absolutely add px to the end if it’s getting to you. The only things that would make this worth reconsidering are:

  1. You’ve got to spend all that time to type out 2 extra characters (ugh :roll_eyes:)
  2. 2 characters, repeated as many times as you use 0, can add quite a bit of size to your document if it’s big enough, so it’s best to omit them if they’re not necessary.

BUT like I said - if you want them, go add them!

5 Likes