Lesson

CSS Margins

10 min reading
Free Course

CSS Margins: Outer Spacing, Centering, and Margin Collapse

CSS margins create transparent outer space outside an element's border, pushing neighboring elements away. Controlling vertical and horizontal margins separates headings from paragraphs, centers fixed-width containers on wide screens, and keeps page rhythm consistent.

Margin Shorthand and Auto Centering

You can pass one to four values to margin (clockwise from top: top right bottom left):

  • 1 value: margin: 16px; applies to all four sides.
  • 2 values: margin: 16px 24px; sets top/bottom to 16px and left/right to 24px.
  • 4 values: margin: 8px 16px 24px 16px; sets top, right, bottom, left individually.
  • Horizontal Centering: Setting margin-inline: auto; (or margin: 0 auto;) on a block element with a max-width centers it automatically inside its parent.
.page-container {
    max-width: 960px;
    margin: 0 auto;
    padding: 0 16px;
}

.section-heading {
    margin-top: 32px;
    margin-bottom: 12px;
}

.card-stack > * + * {
    margin-top: 16px;
}

Understanding Vertical Margin Collapse

When two vertical block elements touch—say an h2 with margin-bottom: 24px; right above a p with margin-top: 16px;—their margins do not add up to 40px. Instead, they collapse into the larger value (24px). Notice that margins never collapse inside Flexbox or Grid containers!

Common Mistakes to Avoid

  • Trying to center a span or inline element with margin: 0 auto;: Auto horizontal margins only center block-level elements that have an explicit width or max-width.
  • Adding top and bottom margins to pure inline tags like span: Vertical margins are ignored on display: inline elements; use inline-block or block.
  • Forgetting gap in Flex/Grid layouts: Inside Flexbox or Grid, prefer gap: 16px; instead of fragile child margins.

Frequently Asked Questions

When should I use margin instead of padding?

Use margin for spacing outside an element's border between separate components, and padding for breathing room inside an element's background and border.

Are negative margins valid in CSS?

Yes. Negative margins like margin-top: -12px; pull an element closer or create overlapping badges, though overusing them can obscure sibling text.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
CSS Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum