Margin vs Padding
padding adds space inside an element, between its content and its border. margin adds space outside an element, separating it from its neighbors.
Margin and Padding Compared
<style>
.box {
background: #eef4fb;
border: 2px solid steelblue;
padding: 20px;
margin: 20px;
}
</style>
<div class="box">Padding is inside the border, margin is outside.</div>Shorthand Notation
Both properties accept one, two, three, or four values to control each side, always in clockwise order starting from the top.
Shorthand Values
| Values | Meaning |
|---|---|
| margin: 10px; | All four sides: 10px |
| margin: 10px 20px; | Top/bottom: 10px, left/right: 20px |
| margin: 10px 20px 30px; | Top: 10px, left/right: 20px, bottom: 30px |
| margin: 10px 20px 30px 40px; | Top, right, bottom, left (clockwise) |
Individual Sides
.box {
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;
}Centering with Auto Margins
Setting margin-left and margin-right to auto on a block element with a defined width centers it horizontally within its parent.
Centering a Block
<style>
.centered {
width: 200px;
margin: 0 auto;
background: #ffeaa7;
padding: 10px;
text-align: center;
}
</style>
<div class="centered">Centered box</div>Margin Collapsing
Vertical margins between adjacent block elements can "collapse" into a single margin equal to the larger of the two, rather than adding together. This only happens with vertical margins, never horizontal ones.
Best Practice
Prefer padding for space inside a component’s own border, and margin for space between separate components. Being consistent about this makes spacing bugs much easier to track down.