Difference: margin vs padding?

Padding is the space inside an element, between its content and its border, and it shows the element's background. Margin is the space outside the border, separating the element from its neighbors, and it is always transparent. Padding also enlarges the clickable area; margin does not.

Side by side

PaddingMargin
LocationInside the borderOutside the border
BackgroundShows the element's backgroundTransparent
ClickablePart of the elementNot part of it
Negative valuesNot allowedAllowed
autoNot allowedAllowed (margin: auto centers)
CollapsingNever collapsesVertical margins can collapse

When to use which

  • Padding: breathing room inside a button, card or input; increasing touch target size.
  • Margin: spacing between separate components, centering a block (margin-inline: auto).
  • In flex and grid layouts: prefer gap for spacing between children; it avoids margin hacks and never collapses.

Shorthand order

Both follow clockwise order: top right bottom left.

  • padding: 8px 16px (vertical, horizontal)
  • margin: 0 auto
  • Logical properties adapt to writing direction: padding-inline, margin-block.

Interview tip

Mention margin collapsing and the gap property; together they explain most surprising spacing bugs.

Code example

html
1<style>
2 body { font-family: system-ui; }
3 .btn { background: #2b4bff; color: white; border: 2px solid #0b1020; font: 600 15px system-ui; }
4 .padded { padding: 14px 24px; } /* bigger box, bigger click target */
5 .margined { margin: 14px 24px; padding: 2px 6px; }
6 .outline { outline: 2px dashed #e11d48; display: inline-block; }
7 .row { display: flex; gap: 12px; } /* spacing between children: use gap */
8 .row div { background: #fef9c3; padding: 8px; border: 2px solid #0b1020; }
9</style>
10<p>Padding grows the button itself (blue area):</p>
11<span class="outline"><button class="btn padded">Padding</button></span>
12<p>Margin adds empty space outside it (between blue and red outline):</p>
13<span class="outline"><button class="btn margined">Margin</button></span>
14<p>gap between flex items:</p>
15<div class="row"><div>One</div><div>Two</div><div>Three</div></div>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app