Encodera

Thanks for reading!

Donate to the site — we work hard for you.

HTML & CSS reference

margin

The outer spacing of an element — the distance to its neighbors.

Syntax

margin: top right bottom left;

Values

ParameterTypeDescription
lengthlengthOne value for all four sides: `16px`.
autokeywordTakes all the free space; `margin: 0 auto` centers a block of a given width.
two valueslengthVertical and horizontal: `10px 20px`.
four valueslengthClockwise from the top: `10px 20px 30px 40px`.

Examples

Different ways to write margins:

<style>
  .box { background: lightskyblue; padding: 6px; }
</style>
 
<div class="box" style="margin: 16px;">16px on every side</div>
<div class="box" style="margin: 0 40px;">0 vertically, 40px horizontally</div>
<div class="box" style="margin-top: 24px;">Only the top margin</div>

Centering a block:

<div style="width: 200px; margin: 0 auto; background: gold; padding: 6px;">Centered with auto</div>

Notes

The vertical margins of neighboring blocks collapse: of 20px and 30px only 30px remain. Margins can be negative. Inside flexbox and grid it is usually easier to set spacing with gap.

See also

  • padding — The inner spacing between the content and the border of an element.
  • gap — The gaps between items in flexbox and grid.
  • margin-inline — Logical properties: sizes and spacing by the direction of the text instead of left, right, top and bottom.
  • box-sizing — Whether `width` and `height` include the padding and the border.

Related recipes

In the tutorial

  • The box model — What an element consists of in CSS — content, padding, border and margin, sizes, centering and box-sizing.

Thanks for reading!

Donate to the site — we work hard for you.