In CSS, knowing when to use margin vs. padding isn’t always the easiest thing to understand. Let’s dive right in to hopefully clear up any confusion you may have.
Margin in CSS
Margins will push elements away from where ever you are setting a margin value. With margins, the box will never change in size.
Visualize a box. Now, with that box, stack another box on top. If you can a margin bottom on the box on the top, there will be a gap between these boxes.
Padding in CSS
Padding values will only control content within the element that it is set on. With padding, the box may change size.
It’s common to have this CSS set globally for your website:
* {
box-sizing: border-box;
}
The purpose for this is to have your padding not impact the overall size of the content where it is set.
<style>
.box {
width: 100px;
height: 100px;
padding: 10px;
}
<div class="box">This is a box</div>
</style>
In the above example, the box will be 120px;
all around. You get 100px
from the width and height and 10px
on the left, right, top and bottom. If box-sizing: border-box;
is globally, or scoped to the .box
class. The box will be 100px
all around.
Margin vs padding
So now that you hopefully have a better understanding of what margin and padding is, let’s explore why you would want to use each.
If you want to space elements from each other, use margin. If HTML elements don’t have a background or border, margin and padding effectively look the same.
However, the moment you add a border or background to an element, you’ll likely need to refactor your code because the intersection between the two elements won’t always look how you intended it to.
Now think about an element with text inside and a background set. Without any padding, the text will be flush against the background. You use padding in order to space out the text from the edge of the bounding box.
Caveats / best practices
- If you have two stacked elements, one with
margin-bottom
and one withmargin-top
, either themargin-bottom
value or themargin-top
value won’t actually do anything. This is referred to as collapsed margins. - You may want to set a rule for when to use
margin-top
vsmargin-bottom
. This can help prevent collapsed margins and make it easy to develop on your website or application. - Margins can accept negative values, which instead of pushing other elements away, will bring them closer. The minimum padding you can set is 0. There is no such thing as negative padding.