CSS propertyBox model

margin

Sets the outer space between an element and its neighbors.

Initial value
0
Inherited
No
Animatable
yes, as a length
Applies to
all elements except internal table elements
JavaScript
element.style.margin = "16px auto"
On this page

Example

#
CSS
.page {
  max-width: 420px;
  margin: 0 auto;
}

.page h2 {
  margin-bottom: 8px;
}
Preview

Definition and usage

#

The margin property is shorthand for four margins: margin-top, margin-right, margin-bottom, and margin-left. A margin is transparent space outside the border that pushes an element away from others.

One value sets all four sides, two set the vertical and horizontal sides separately, three set the top, the horizontal sides, and the bottom, and four set the top, right, bottom, and left in turn (clockwise). A horizontal auto centers a block that has a defined width.

Watch out for margin collapsing: the vertical margins of adjacent blocks don’t add up, the larger one simply wins. This doesn’t happen inside flex or grid containers.

Syntax

#
Syntax
margin: <top> <right>? <bottom>? <left>?;

Values

#
  • 0

    No margin. The parent’s background stripes sit right up against the element.
  • 16px

    <length>

    An equal 16px margin on every side.
  • 8px 40px

    vertical horizontal

    8px on top and bottom, 40px on the sides.
  • 12px auto

    auto

    A horizontal auto centers a block that has a known width.
  • -8px

    negative value

    A negative margin pulls the element closer, or even pushes it outside its parent.

Values in practice

#

0

No margin. The parent’s background stripes sit right up against the element.
.demo { margin: 0; }

16px

An equal 16px margin on every side.
.demo { margin: 16px; }

8px 40px

8px on top and bottom, 40px on the sides.
.demo { margin: 8px 40px; }

12px auto

A horizontal auto centers a block that has a known width.
.demo { margin: 12px auto; }

-8px

A negative margin pulls the element closer, or even pushes it outside its parent.
.demo { margin: -8px; }

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Use gap for spacing between items in a row or grid, not margins.
  • The logical properties margin-inline and margin-block also work correctly in right-to-left languages.

Related entries

#

Spotted a mistake or missing an example? Write to us.