OnlineCBT Logo OnlineCBT
CSS Tutorial
CSS · LESSON 15

Margin Collapsing and Negative Margins

By Ratan Updated: 15 Oct 2026

Understand how adjacent vertical margins collapse and how negative margins alter layout positioning.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Understand why vertical margins do not always add

In normal block flow, certain adjoining vertical margins collapse into one margin. For two positive collapsing margins, the result is the larger margin rather than their sum. Flex and grid item margins do not collapse with each other in this way.

.first { margin-bottom: 24px; }
.second { margin-top: 16px; }

Two adjoining ordinary block siblings can have 24px between them, not 40px. This behavior can surprise you if you calculate all vertical spacing by addition.

Parent-child collapse

A first child's top margin may collapse with its parent's top margin when nothing separates them under the relevant rules. A border, padding or a new formatting context can prevent particular parent-child collapse relationships. Do not add an unexplained 1px border simply as a mystery fix; choose a layout rule that reflects the design.

.section {
  display: flow-root;
}
.stack {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
.stack > * { margin: 0; }

flow-root establishes a block formatting context. The stack example uses explicit flex gap for predictable child separation instead of relying on collapsing margins.

Negative margins

A negative margin can pull a box toward a neighbor or expand its used space in a particular layout. It is not the same as transform:translate, because it participates in layout. For collapsing margins involving positive and negative values, the calculation differs from simply taking the largest absolute value. Avoid using negative margins to cover an unexplained sizing error.

Debugging sequence

Inspect the parent's layout mode, then the child's margin, and check whether borders or padding separate their edges. Temporarily turn the parent into a flex column with gap to determine whether margin collapse explains the spacing. Restore the intended layout once the cause is understood.

Practice

  1. Place 24px bottom margin above 16px top margin in block flow and inspect the gap.
  2. Repeat with a flex-column parent and zero margins plus gap:24px.
  3. Add padding-top to a parent whose first child's margin appeared to escape it and observe the change.
  4. Explain why a negative margin affects neighboring layout while a transform normally does not reserve a new position in normal flow.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat