Margin vs Padding

Margin vs Padding

Image for post

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:

Image for post

  • 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:

Image for post

  • You want to increase the size of the element. Example: if you want to increase the size of a button:

Image for post

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:

Image for post

  • You want to center an element. If you give ?margin: auto? to an element with fixed width, it will center that element horizontally (and vertically too if using flexbox, check this tutorial if you are new to Flexbox):

Image for post

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/

1

No Responses

Write a response