Though it may not be an age-old question, it so happens to decide when to use margin vs padding may not be as trivial for some.
Inexperienced web designers may get caught up in a spacy situation when trying to craft elegant CSS to not only impress the users but to deal with all the responsive media queries.
it does not help that in many cases the end effect of using either seemingly produces the same result. It this is truly the case, the question begs. Why did the designers of CSS decide they need both a margin and a padding property?
What’s the Difference Between Margin vs Padding?
The CSS margin is used to regulate the space around an HTML element. This space would be described as the white space surrounding the element’s border or boundary.
The aim of the margin is to how much space there should be between the subject element and other elements surrounding it.
The space around the element can be defined equally around all sides (top, right, bottom, and left) or they can be set individually.
The CSS padding property is used to control the space around content within an element. The space in question here lies within the border of the element.
Just like the CSS margins, you can set the padding within elements equally at the top, right, bottom, and left sides or you can set them individually.
Basically, the padding property clears the content from the containing box while margin clears the containing box from other elements.
Some Practical Use Cases for Margin vs Padding
1. One ideal place you can use padding vs margin is when you want the white space around the content to retain the same color as the content.
A good example is when you want to use, tabs, pills, etc where you use mouseover effects to change the content color with a space allowance.
2. An ideal place to use margin is where you do not want to tamper with the layout of the content. The padding takes space inwards. This, however, depends on whether you are using a box-sizing with content-box or border-box. Check out this article on box-sizing for more details.
3. You can add additional styling to the border and content. A good example would be around images where you might want some white space to complement a visible border.
This is also true for other element types where you make the border visible. In almost all of these cases, you may want to add some padding for aesthetics. Where the border is kept invisible it may not matter.
And now for those with the creative bone, however you best you achieve your goals (in the most efficient way) could make a case for the reasons you choose to use margin vs padding. As we know in CSS, creative use of properties on various elements has seen some very clever UI effects come into practice.
Ref: [ 1 ]