CSS · Layout and visual systems
What is margin collapsing and how do you control it?
Short answer
Vertical margins of adjacent block boxes can collapse into a single margin, using the largest positive value. It happens between siblings, through parents, and across empty blocks, but not in flex, grid or new block formatting contexts.
Margin collapsing applies to vertical margins in normal block flow. Instead of adding margins together, the browser combines them. Two adjacent paragraphs with 1rem top and bottom margins are separated by 1rem, not 2rem.
p {
margin: 1rem 0;
}
.parent {
margin-top: 2rem;
}
.child {
margin-top: 1rem;
}When collapsing happens
- Adjacent siblings in normal flow
- A parent's top margin with its first child's top margin when nothing separates them
- A parent's bottom margin with its last child's bottom margin
- Empty blocks whose top and bottom margins meet
- Not between flex items, grid items, floats or absolutely positioned boxes
- Not across a border, padding, inline content, clearance or a new block formatting context
The collapsed result is the largest positive margin; negative margins participate with more complex rules. One way to stop a parent's margin collapsing with its children is display: flow-root, which creates a new block formatting context without the side effects of overflow: hidden.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Which margins collapse and which do not?
- 2How do you prevent a child's margin from collapsing through its parent?
- 3Why do margins not collapse in a flex container?
- 4What happens with negative margins?
Say it in the interview
Vertical margins in normal block flow can collapse into one margin, usually the largest positive value. That happens between siblings, between a parent and its first or last child, and through empty blocks. It does not happen in flex or grid containers, with floats or absolute positioning, or across padding and borders. If I need to stop it cleanly, display flow-root is my preferred tool.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live CSS mock interview and get scored feedback on depth, clarity and confidence.