Using Margin vs Padding in CSS
For a novice CSS developer, the terms margin and padding can be somewhat confusing.
Both terms are referring to the space between certain elements.
However, there is a big difference between margin and padding and knowing the differences and using them accordingly will help a developer in making better decisions in their design.
So, what is a Margin in CSS?
A margin is referring to the vertical and horizontal space between two elements.
Without having set margins, your elements would bump into each other.
You can define and set margins for the top, bottom, left and right side of your element.
The margin basically clears an area around your element, which is transparent without a background color.
And what is Padding in CSS?
Padding is the vertical and horizontal space that is set on the inside of your box.
It refers to the outer space of your content in your element.
You can set the padding for the top, bottom and right and left sides of your property independently.
Therefore, you can center your text, or have it set to the right or left side or your element, or set it to the top or bottom of your element.
Margin and padding may seem very similar due to the fact they both create space around your element, but there are specific reasons to use one or the other.
You want to use margins when you want your spacing to appear outside of your text box, especially when you are using borders.
Also if you are using background colors or images and you do not want them to invade the space of your element.
Padding behaves very differently in these circumstances.
Padding is contained inside your borders; therefore if you want all of your space inside the border, you would want to use padding.
And if you are using a background color or image and you want that color and/or image to continue behind your element you would want to use padding.
How to use Margin VS Padding
To summarize, margins separates your elements from each other and away from the edges which adds space to the outside of your elements.
And padding adds space and separates your text and content in the inside of your element.
It is important to use margins and padding even if you do not have a border to ensure the correct spacing between your elements.