Margin collapse and negative margins
Definition and purpose
Adjacent vertical margins of normal-flow blocks can collapse into a single margin in horizontal writing mode. This is not simple addition.
Adjacent positive margins
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> div { height: 20px; } #a { margin-bottom: 20px; } #b { margin-top: 30px; } </style> </head> <body> <div id="a">Sample A</div> <div id="b">Sample B</div> </body></html>The measured gap is 30px, although computed margins remain 20px and 30px.
Syntax and mental model
Two positive adjoining margins of 20px and 30px collapse to 30px. A positive 30px and negative -10px give 20px; two negative margins use the more negative value. Parent-child collapse can occur without separating content or borders. Flex and grid items do not collapse margins with one another; their layout is taught later.
A negative margin
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> div { height: 20px; } #a { margin-bottom: 30px; } #b { margin-top: -10px; } </style> </head> <body> <div id="a">Sample A</div> <div id="b">Sample B</div> </body></html>The gap becomes 20px because the positive and negative values combine.
Common mistakes
Avoid assuming every margin collapses, or that negative margins merely shrink the element. They affect placement and can overlap other content.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Minimum and maximum sizes. Next lesson: Overflow and scroll containers.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Margin collapse and negative margins — knowledge check
Five questions on margin collapse and negative margins.
What is the collapsed gap for 20px and 30px positive adjoining margins?
What is 30px collapsed with -10px?
What do two negative adjoining margins -10px and -20px collapse to?
Do adjacent flex items collapse margins with one another?
What can a negative margin cause?