DevAcademy
LearnCSSMargin & Padding
BeginnerCSS

Margin & Padding

Learn how margin and padding control spacing outside and inside an element, including shorthand notation and margin collapsing.

Reading Time

14 min

Lesson

Lesson 11 of 30

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>
Output

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

ValuesMeaning
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>
Output

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.

Interview Questions

Quick Quiz

1. Which property adds space inside an element’s border?

2. What does margin: 10px 20px; set?

3. What does margin: 0 auto; do to a block element with a set width?