Margin vs Padding

Kunal
Frontend Shortcut
Published in
3 min readMar 6, 2018

Margin is an element’s personal space — how much distance the element wants to keep with other elements around it.

Padding is how much an element is away from itself — how much distance an element wants to keep with the elements inside it.

They both are used to create gaps around elements, but they differ in their method of creating that gap. Margin accommodates the gap by pushing adjacent elements away from it, while Padding accommodates the gap by either growing its own size or by shrinking the size of content inside it.

By default, padding will increase the size of the element to accommodate the gap. But if you set “box-sizing: border-box” on the element, then it will shrink the size of the content inside the element to accommodate the gap.

Use padding when:

  • You don’t want your content to touch the edges of the container. Example: you have a bunch of <p> elements inside a div and you don’t want the text inside <p> elements to touch the div’s border:
  • You want the background of the element to be displayed in the produced gap.Example: you have a green and an orange div adjacent to each other, and you want both divs to touch each other, but don’t want their texts to touch each other:
  • You want to increase the size of the element. Example: if you want to increase the size of a button:

Use margin when:

  • You want to have some space around an element, or you don’t want the element to touch other elements around it:

Hope this helps.

If you have any doubt let’s discuss it in comments, or feel free to drop me an email at kunal@supersarkar.com.

Subscribe at supersarkar.com for new tutorials every week.

Keep Rocking \m/

--

--

Kunal
Frontend Shortcut

Demystifying life and thinking with first principles. Twitter: twitter.com/KunalBSarkar