Distance Is Key to Interface Health

Margins (external margins) are needed for positioning blocks relative to each other.

1. Centering

If a block has width (width), the margin: 0 auto statement makes the browser divide all available parent space equally left and right. Block stands perfectly centered.

2. Negative Margins

Unlike all other properties, margins can have a minus sign.

.overlapping-item { margin-top: -20px; } /* Element will overlap the top neighbor */

3. Insidious Margin Collapse

This is the most " annoying " moment for beginners. If the top block has margin-bottom: 50px and the bottom has margin-top: 30px, the distance between them will be 50px, not 80px.

  • Rule: Vertical margins of adjacent blocks consume each other, choosing the larger.
  • Exception: Collapse DOESN'T work for Flexbox and Grid.
Caution

Collapse also happens between first child and parent. If parent has no border or padding, child's margin will " fall out " and push the parent itself.