What is margin collapsing? Give a sibling scenario and prevention.

This tests understanding of vertical margin combination in normal flow. A strong answer defines collapsing, gives a sibling paragraph example where the larger margin wins, and names a block formatting context or padding as prevention.
WHAT THIS TESTS: This question evaluates whether you understand the CSS box model in normal flow, specifically the rules that govern how vertical margins interact when no separating content or formatting context exists. It reveals if you can distinguish between layout modes and explain why margin behavior differs across contexts.
A GOOD ANSWER COVERS: First, define margin collapsing as the behavior where the top and bottom margins of block-level boxes combine into a single margin equal to the largest of the adjacent values. Second, describe the adjacent sibling case: when two block elements such as paragraphs follow one another, their shared margin resolves to the larger of the two rather than the sum. Third, explain prevention methods: establishing a new block formatting context, adding border or padding, inserting inline content, or switching the container to flex or grid display because margins do not collapse in those layout modes. Fourth, note that negative margins participate by adding the largest positive to the smallest negative value.
COMMON WRONG ANSWERS: A major red flag is stating that margins always add together or that horizontal margins collapse. Another is claiming that floated or absolutely positioned elements collapse margins, when MDN explicitly states they never do. Candidates also err by suggesting margin collapse occurs in flex or grid containers, or by confusing padding and border fixes with margin fixes.
LIKELY FOLLOW-UPS: An interviewer might ask how margin collapsing behaves with negative margins, or why a parent and first child margin-top seem to escape the parent boundary. They may also ask you to compare inline-block, flex, and grid containers regarding margin behavior, or to debug a layout where expected spacing is missing.
ONE CONCRETE EXAMPLE: Imagine two adjacent paragraph elements in normal flow. The first has a margin-bottom of 2rem and the second has a margin-top of 1rem. Instead of 3rem of space between them, the browser renders 2rem because the margins collapse. To prevent this, you could establish a new block formatting context around one paragraph, or change the parent container to display flex so that the margins remain separate and the total space becomes 3rem.
Source: developer.mozilla.org
Read the original → developer.mozilla.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.