margin

Definition

The margin CSS property sets the outer spacing of an element, creating space between the element and its neighboring elements. Margins are transparent and don’t have a background color, making them perfect for creating visual separation and breathing room in layouts. The margin property is part of the CSS box model and affects the element’s positioning relative to other elements.

Syntax

.card {
  margin: 2rem auto;
  max-width: 48rem;
}

Values

  • <length>: fixed spacing using px, rem, etc.
  • <percentage>: resolves against the width of the containing block.
  • auto: absorbs available space—commonly used to center block elements horizontally.
  • Specify 1–4 values to target sides clockwise (top, right, bottom, left).

Practical Examples

.card {
  margin: 2rem auto;
  padding: 1.5rem;
  max-width: 42rem;
}

Auto margins center containers while fixed values create predictable breathing room.

HTML

Without margin auto

Block sticks to the left edge.

margin: 0 auto

Centered using auto side margins.
Code
<div class="space-y-6">
  <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm" style="max-width: 640px;">
    <h4 class="text-sm font-semibold text-slate-600">Without margin auto</h4>
    <div class="bg-slate-100 p-6 text-sm text-slate-700">Block sticks to the left edge.</div>
  </div>
  <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm" style="max-width: 640px;">
    <h4 class="text-sm font-semibold text-slate-600">margin: 0 auto</h4>
    <div class="bg-slate-100 p-6 text-sm text-slate-700" style="margin: 0 auto; max-width: 420px;">Centered using auto side margins.</div>
  </div>
</div>

Tips & Best Practices

  • Use logical properties (margin-inline, margin-block) for international layouts when appropriate.
  • Reset flex or grid items with margin: 0 before relying on gap to manage spacing.
  • Combine with CSS functions like clamp() to make outer spacing responsive.

Accessibility & UX Notes

Consistent spacing improves readability and helps users with cognitive load by grouping related content.

Browser Support

Margin shorthand is universally supported.

  • padding for internal spacing.
  • gap for controlling spacing in flex/grid containers.
  • margin-inline/margin-block logical counterparts.