Margin vs Padding in CSS — What’s the Difference?

Learn about the difference between margins and paddings in CSS.

Margin vs. Padding

Let’s start with the shortest definition:

  • margin adds spacing outside HTML elements’ border
  • padding adds spacing inside HTML elements’ border

When you apply margin or padding to an HTML element, this is how they affect the element differently:

Illustration of difference between margin and border in CSS

With the conceptual illustration above in mind, let’s apply this knowledge to a real HTML element.

Above is a simple <button> element inside a <div> container.

The button has:

  • 24px margin that adds space around the button and pushes it away from the border of the parent element it sits inside.
  • 4px border
  • 16px padding that adds space between the button’s border and its content.
  • Content (in this case, the text label: Button)
button {
    padding: 16px; 
    margin: 24px; 
    border: 4px solid #282828;
}

Both the margin and padding properties control whitespace. However, they have the opposite function in terms of how they apply it.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on