Box

margin

margin sets the space outside a box's border (the outer spacing). It separates the box from its neighbors, and auto can center it.

Syntax

[ <length-percentage> | auto ]{1,4}

Preview

Presets
Drag the bottom-right corner to resize

Code

.box {
  margin: 24px 48px;
}

Controls

margin
Same value for every side
margin-top24px
margin-right48px
margin-bottom24px
margin-left48px

About

The preview on this page paints the margin orange, as browser developer tools do. On a real page the margin is transparent and shows the parent's background.

Writing the value

As with padding, list one to four values: one for all sides, two for top/bottom and left/right, three for top, left/right and bottom, and four clockwise from the top.

  • A length such as 24px, or %: leaves that much space. A % is a share of the parent's width, even for top and bottom.
  • A negative value: pulls the box that way, letting it overlap its neighbors. In the preview, the orange area shrinks inside the box, and its dashed edge shows on top of the box.
  • auto: takes up the leftover space. On a block element with a set width, margin: 0 auto makes the left and right equal, centering it.

Vertical margins collapse

Between block elements stacked vertically, the bottom margin of one and the top margin of the next are not added; only the larger one remains (margin collapsing). This does not happen inside flex or grid containers.

Comments