Teaching the order of margins in CSS

At codebar this week, I was paired with a graphic designer who was just starting her HTML & CSS learning journey. I really enjoyed working with her because she wanted to understand everything, and because of this, I found a nice way to explain the order of margins in CSS.

Margins are added to the outside of an element using four different properties like this:

  • margin-left: 1em;
  • margin-right: 1em;
  • margin-top: 1em;
  • margin-bottom: 1em;

This can also be written in several different ways using these shorthand methods:

  • margin: 1em;
  • margin: 1em 1em;
  • margin: 1em auto 1em;

Codebar's tutorials introduce the shorthands very early on (in the second lesson), which is often before students have fully grasped how CSS works, so I find myself explaining these shortcuts a lot. It isn't surprising that the shorthand values can be difficult to remember—I know I had trouble remembering them when I started out.

Fig 1.0 The order of margins

Let's look at these margin values: margin: 1em 2em 4em 2em;

As figure 1.0 illustrates, the first value in the set is equivalent to the top of the square, working clockwise round so that each value represents a different side. So: 1em = margin-top, 2em = margin-right, 4em = margin-bottom, 2em = margin-left.

This seems pretty straight forward, but the two alternative shorthand methods are slightly more difficult to remember without the diagram.

Look at this margin: 1em 3em; We know it's shorthand for all four values (top, right, bottom, left), but how?

Fig 1.1 The order of margins and their pairs

Using figure 1.0 we know that 1em = margin-top and 3em = margin-right, but what about the bottom and left values? Figure 1.1 illustrates how the values are paired, so when you are only given two values, you can pair them up. The top value is equal to the bottom value and the left and right values are equal. So, back to the example: margin: 1em 3em; We know that 1em = margin-top because that's the starting point, and 3em = margin-right. It may not be immediately clear what the bottom value is, but we know from figure 1.1 that it is paired with top, so margin-bottom = 1em. Similarly, the left value pairs up with the right value, so margin-left = 3em.

Now let's look at this shorthand method margin: 1em auto 3em. Using the diagram and starting at the top, we know that 1em = margin-top, auto = margin-right, and 3em = margin-bottom. Easy peasy. Since the left value hasn't been accounted for yet, we pair it up with the right value, so margin-left also has the value auto.

The last shorthand method is margin: 1em; This is simple: every side of the square is equal to 1em. That's just one of those things you have to remember. Hopefully, I can make margins clearer to a few more people at codebar using this diagram.

Tags: