CSS Margins & Margin Collapse
Margins create space OUTSIDE elements. They push other elements away. Understanding margin shorthand, auto centering, and the quirky behavior of margin collapse is essential for predictable layouts.
15 min•By Priygop Team•Updated 2026
Margin Properties
- margin-top, margin-right, margin-bottom, margin-left — Set individual sides
- margin: 16px — All four sides equal
- margin: 16px 24px — Top/bottom 16px, left/right 24px
- margin: 10px 20px 30px 40px — Top, right, bottom, left (clockwise)
- margin: 0 auto — Centers a block element horizontally (element needs a width set)
- Negative margins — margin-top: -20px pulls the element upward. Useful but tricky
- Margin collapse — When two vertical margins touch, they collapse into the larger one (not both!)
Margin Collapse Explained
Margin Collapse Explained
/* Margin collapse example */
.box-a { margin-bottom: 30px; }
.box-b { margin-top: 20px; }
/* You might expect 50px gap (30 + 20)
But you get 30px — they collapse to the LARGER value! */
/* Margin collapse only happens vertically (top/bottom),
NOT horizontally (left/right) */
/* Ways to prevent margin collapse: */
.parent {
/* Any of these prevents collapse: */
overflow: hidden; /* Creates new formatting context */
padding-top: 1px; /* Separates margins */
border-top: 1px solid transparent;
display: flex; /* Flex containers prevent collapse */
display: grid; /* Grid containers prevent collapse */
}
/* Centering with auto margins */
.container {
max-width: 1200px;
margin: 0 auto; /* Top/bottom 0, left/right auto = centered */
}Tip
Use margin: 0 auto with a max-width for page containers — it's the classic centering pattern. The auto left/right margins split remaining space equally. This works on any block element with a defined width.
Diagram
Loading diagram…
Every element follows the box model — content + padding + border + margin
Common Mistake
Expecting margin-bottom: 30px + margin-top: 20px to create 50px of space. Vertical margins collapse — only the larger value (30px) is used. This only happens vertically; horizontal margins never collapse. Use padding or Flexbox gap to avoid this.
Quick Quiz
Key Takeaways
- Margins create space OUTSIDE elements.
- margin-top, margin-right, margin-bottom, margin-left — Set individual sides
- margin: 16px — All four sides equal
- margin: 16px 24px — Top/bottom 16px, left/right 24px