The Difference Between Margin, Border, and Padding

Published June 15, 2014, by @jhendge

Background

Margins, borders, and padding are pretty sweet. But in order to understand the concepts of those and how they operate with HTML and CSS, we first have to lay some groundwork:

  1. All HTML elements can be thought of as boxes.
  2. Take a look at #1 again... think about it. Everything. This list I'm writing in right now is a rectangular box. The header above it is a box and the footer at the bottom is a box. Heck, this entire web page is one big box!
  3. Now that we know a web page is nothing but boxes, we have to arrange them so that they look nice and pretty for users. We don't want people getting sick when they're looking at our pages.

Now that we know the basics, let's refer to The CSS Box Model. Without going rogue technical on you, let's just say that the box model is a massive box that hugs the little HTML boxes and consists of margins, borders, and padding. The images below give a great visual representation (thanks W3 Schools and css-tricks.com!) Now, what exactly are these three?

Margins

Let's start from the back (or largest box if you prefer to think of it that way) and work our way forward. Margin is the biggest box and it is totally transparent. We can't see it. It has no background color. But it's there. Trust me, it's there. And it's really important. It pretty much determines how much space there is between HTML elements. Wow, yeah... this is really important!

But what about borders?

Borders

Don't worry, border, we wouldn't forget about you. Since you can't see the margin, the border is the first real box that we see. It takes its place around padding and content, and is typically the same color as them. That being said, the color of the border can be changed so that it more obviously defines a space.

Finally, what is padding all about?

Padding

So what is this funny padding business all about? Padding surrounds the content and is the space between an element's border and the content within it. Padding is nice because it helps to make things easier to read, like hopefully this!