The margin property

margin is the outer spacing: transparent space around an element's border that pushes its neighbours away. It is a shorthand for margin-top, margin-right, margin-bottom and margin-left.

Syntax

margin: 16px;               /* all four sides */
margin: 16px 24px;          /* top and bottom | right and left */
margin: 8px 24px 16px;      /* top | right and left | bottom */
margin: 8px 16px 24px 32px; /* top | right | bottom | left */
margin: 0 auto;             /* center a block with a set width */
Initial value
0
Inherited
no
Applies to
all elements except internal table elements (rows, cells and so on)

Values

ValueWhat it does
<length>a fixed distance: px, rem, em and so on; it can be negative, and then the element overlaps its neighbour
<percentage>a percentage of the containing block's width — even for the top and bottom margins
autothe browser distributes the free space: margin: 0 auto centers a block with a set width, and in a flex container auto pushes the item away

Example

.box {
  padding: 12px;
  background: #e0f2fe;
  border: 1px solid #0284c7;
}
.a { margin-bottom: 24px; }
.b { margin-top: 16px; }
.centered {
  width: 200px;
  margin: 16px auto;
}
<div class="box a">margin-bottom: 24px</div>
<div class="box b">margin-top: 16px — 24px between the blocks, not 40px</div>
<div class="box centered">margin: 16px auto</div>

Result

▶ Open in HTML Editor

Good to know

  • Vertical margins of adjacent blocks collapse: the larger margin remains, not the sum. There is no collapsing in flex and grid containers.
  • margin is space outside the border; the element's background does not reach it. The inner space between the border and the content is padding.
  • margin: 0 auto only centers a block whose width or max-width is smaller than its parent.
  • Vertical margins on inline elements (span, a) do not push neighbouring lines.

Sources and specification

See also