CSS Concepts

(AKA My back hurts and I'm squinting.)

November 8, 2015

What is the difference between margin, border, and padding?

You may find yourself pondering this question as you begin to learn CSS. It's confusing until it's not, so let me break it down for you.

CSS box-model

Or really, let the above image break it down for you.

The CSS Box Model helps designers position elements by creating 3 means of augmenting or diminishing space.

  1. Margin: the space around the outside of the element. This will determine how closely it can snuggle up to other elements.
  2. Margin diagram
  3. Border: this is the line that you might draw around the element itself. The border can be very thick, very thin, or even 0 pixels wide. But, even if you can't see it, it's still there.
  4. Border-width diagram
  5. Padding: The space between the element and the inside surface of the border. More padding gives the element some breathing room. Less will constrict the border close to the element itself.
  6. Padding diagram

So, when would you use each of these and why?

Say you wanted to have two blocks side by side. You might write the following code:

Which would result in the following blocks:

Blocks

Not super pretty. But they'll do the job. So, let's change the margins so they have a little room between them.

Here I've given Block 1 a margin-left of 40px (pixels). You can see that it now bumps out past its border, and Block 2 can only come within 40px of it on the left.

Blocks

Now, for border. I'm going to give the block different borders so you can see the effect of border width, color, and style.

Block 2 has a thin, dotted, yellow border and Block 1 has a thick, solid, blue border.

Blocks

Finally, let's play with padding. I'm going to increase the padding of Block 1 so you can see the difference.

Blocks

Padding of 50px makes a big difference! Here is the final CSS for the two blocks:

Blocks

And there you have it, my friends. Margins, borders, and padding.