CSSMargin

Margin

Margin is the space outside an element's border, creating distance between elements. Unlike padding (which creates internal space), margin controls how elements are spaced from each other. Margins can collapse in certain scenarios, which is an important CSS behavior to understand.

Margin Syntax

CSS
/* Single value: all sides */
.element {
  margin: 20px;
}

/* Two values: vertical, horizontal */
.element {
  margin: 10px 20px;
  /* top/bottom: 10px, left/right: 20px */
}

/* Three values: top, horizontal, bottom */
.element {
  margin: 10px 20px 15px;
}

/* Four values: top, right, bottom, left (clockwise) */
.element {
  margin: 10px 20px 15px 5px;
}

/* Individual sides */
.element {
  margin-top: 10px;
  margin-right: 20px;
  margin-bottom: 15px;
  margin-left: 5px;
}

/* Auto: useful for centering */
.element {
  width: 300px;
  margin: 0 auto;
  /* Centers element horizontally */
}
Common Margin Patterns

CSS
/* Remove default margins */
* {
  margin: 0;
}

/* Section spacing */
section {
  margin: 40px 0;
  /* Vertical spacing, no horizontal */
}

/* Paragraph spacing */
p {
  margin: 1em 0;
  /* Margins relative to font size */
}

/* Centering with auto margins */
.container {
  width: 800px;
  margin: 0 auto;
  /* Centers container horizontally */
}

/* Negative margins: overlap elements */
.element {
  margin: -10px;
  /* Pulls element 10px inward */
}

/* Combine with positioning */
.element {
  position: relative;
  margin-left: 20px;
  /* Margin offset without affecting document flow */
}
Margin Collapse

Margin collapse occurs when vertical margins between adjacent block elements combine into a single margin equal to the larger of the two. This is a normal CSS behavior that can be surprising at first.

CSS
/* Margin collapse example */
.box1 {
  margin-bottom: 20px;
}

.box2 {
  margin-top: 30px;
}

/* Expected space: 20px + 30px = 50px */
/* Actual space: 30px (larger margin wins) */

/* Prevent margin collapse */

/* 1. Add overflow property */
.container {
  overflow: auto;
}

/* 2. Add padding */
.container {
  padding: 1px;
}

/* 3. Add border */
.container {
  border: 1px solid transparent;
}

/* 4. Use flexbox or grid */
.container {
  display: flex;
  flex-direction: column;
}

/* 5. Use gap property (modern approach) */
.container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  /* gap prevents margin collapse */
}
Note
Margin creates space outside elements. Use margin to control spacing between elements. Remember that vertical margins between block elements collapse to the larger value. For modern layouts, use flexbox/grid with the gap property instead of relying on margins.
Next
Internal spacing: [Padding](/css/padding).