CSS margin Property Explained

What the CSS margin property does, with an example.

Published November 4, 2026

margin sets the space outside an element's border. The shorthand takes 1–4 values (top, right, bottom, left in clockwise order) and auto can centre blocks horizontally.

How it works

Vertical margins between adjacent blocks collapse into the larger one. Negative margins pull elements closer.

margin: 0 auto centres a block that has a width.

Values and effects

margin: 10px; → all sides
margin: 10px 20px; → vertical, horizontal
margin: 10px 20px 30px 40px; → top right bottom left
margin: 0 auto; → centre horizontally

Practical examples

Centre a container

.container { max-width: 960px; margin: 0 auto; }

Spacing between sections

section + section { margin-top: 3rem; }

Logical properties

.card { margin-inline: 1rem; margin-block-end: 2rem; }

Common mistakes

  • Expecting vertical margins to add up (they collapse).
  • Using margin where padding belongs.
  • Using margin: auto vertically in non-flex blocks.

Key takeaways

  • margin in one line: margin sets the space outside an element's border.
  • Inspect it live in DevTools → Styles.
  • Test across browsers and screen sizes.

FAQ

Why do margins collapse?

Adjacent vertical margins combine into the larger one by design.

Is margin supported in all browsers?

Yes in all modern browsers; check caniuse.com for edge cases.

More CSS articles