CSS margin vs padding explained

The CSS margin properties are used to define the outer space around an element, which is rendered on the browser after the border style.

Meanwhile, CSS padding properties are used to define the inner space around an element, which is rendered on the browser before the border style.

The differences between margin and padding are seen clearly when you add the following HTML element to your browser:

<div style="
  background-color: violet;
  border: 5px solid brown;
  padding: 10px;
  margin: 20px;
  Hello World!

The output of the HTML above will be as shown below. Notice the box model on the right bottom side of the page:

Because the padding properties define the space inside the border, it will have the same color fill as the background color of the element.

On the other hand, margin properties are defined outside of the border, so they won’t be affected by the element’s background color.

When to use margin or padding

The margin properties are commonly used to define the position of an element relative to other elements, If you want to add a space between one <div> element and the other, then it’s recommended to use margin properties.

Meanwhile, if you’d like to add some space around an element to make it stand out or easier to read, then use the padding properties.

There is no hard line about when to use margin or padding in creating websites, so you can use your own judgment about when it’s time to add margin or padding properties.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.