Use padding for space inside a box’s border, margin for space outside it, and gap for repeated space between flex or grid items. The background paints through padding; it does not paint through margin.

Working example

See the border, padding and marginLink

HTML and CSS

HTML

<div class="stage">
  <div class="card">
    White padding is inside the blue border. Gray space outside it includes
    margin.
  </div>
</div>

CSS

.stage {
  padding: 1rem;
  background: #e2e8f0;
}
.card {
  margin: 1rem;
  padding: 1.5rem;
  border: 3px solid #2563eb;
  background: white;
}

Edit HTML or CSS to update the preview as you type. Copy code snippet copies the selected tab. Preview spacing and font defaults are not included.

Use gap between repeated itemsLink

HTML and CSS

HTML

<div class="items"><span>HTML</span><span>CSS</span><span>Layout</span></div>

CSS

.items {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}
.items span {
  padding: 0.8rem;
  background: #dbeafe;
}

Edit HTML or CSS to update the preview as you type. Copy code snippet copies the selected tab. Preview spacing and font defaults are not included.

Account for sizing

With box-sizing: border-box, a declared width includes padding and border. Margin stays outside that width. Intrinsic content and minimum sizes can still cause overflow; box sizing does not make every layout fit automatically.

Margins can collapse

Adjacent block margins in normal flow may collapse rather than add. Two positive margins collapse to the larger value; negative margins complicate the result. This is not one declaration being ignored. Flex and grid item margins do not collapse this way.

A gap belongs to the container and does not add space at the outside edges. Use container padding when the group also needs breathing room. Follow the box model path, then compare margin, padding and gap.

Sources

Reference 1 Reference 2 Reference 3 provide the technical details and current compatibility information.