margin

margin is a shorthand for the four physical margins outside an element’s border. Margins are transparent and do not extend its painted background.

See the outside space

The child’s 16px margin creates space around its blue background. The flow-root parent keeps the vertical margins from collapsing out of the container.

Compare marginLink

HTML and CSS

HTML

<div class="parent">
  <div class="child">Margin is outside this blue box.</div>
</div>

CSS

.parent {
  display: flow-root;
  background: #e2e8f0;
}
.child {
  margin: 16px;
  background: #dbeafe;
  padding: 0.5rem;
}

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.

Center a narrower block

Auto side margins share available horizontal space. The block has a maximum width so there can be space left to share.

Center a narrower blockLink

HTML and CSS

HTML

<div class="card">
  This card centers when its container is wider than 18rem.
</div>

CSS

.card {
  max-width: 18rem;
  margin: 1rem auto;
  padding: 1rem;
  background: #eff6ff;
}

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.

Values and shorthand order

The four longhands initially use 0 and are not inherited. One value sets all sides; two set top/bottom then left/right; three set top, left/right, bottom; four run top, right, bottom, left. The shorthand resets all four sides. Lengths, percentages, auto, and negative margins are allowed.

Percentages resolve against the containing block’s inline size, including top and bottom margins. Auto margins depend on layout; they do not generally vertically center a normal block.

Why spacing looks different

Adjacent block vertical margins can collapse; flex and grid item margins do not collapse that way. Top/bottom margins do not push apart ordinary non-replaced inline boxes. Negative margins can overlap content, so test focus and readability.

Use gap for spacing between flex or grid items and padding for inside space. Logical margin-inline and margin-block follow writing mode when physical side names are not what you intend.

Sources and browser support

MDN: margin describes the syntax and links to the specification and compatibility data. Check individual values in that table when supporting older browsers.