Beginner LevelCSS & Modern Layouts
What is CSS margin collapse and when does it occur?
❓ Interview Prompt: Explain vertical margin collapsing between adjacent siblings and parent-child elements.
Margin collapse occurs when vertical margins of adjacent block-level elements combine into a single margin equal to the larger of the two (not their sum).
When It Happens:
1
Adjacent siblings: Top margin of second element collapses with bottom margin of first.
2
Parent and first/last child: If the parent has no border, padding, or BFC, the child's margin "leaks" outside the parent.
3
Empty blocks: Top and bottom margins on an empty element collapse together.
When It Does NOT Happen:
•
Elements with
overflow: auto/hidden (creates Block Formatting Context).•
Flex or Grid children (flex/grid formatting contexts prevent collapse).
•
Elements with padding or border separating the margins.
Code Implementation Example
css
/* Margins collapse: rendered gap is 24px, not 40px */
.box-a { margin-bottom: 24px; }
.box-b { margin-top: 16px; }
/* Prevent collapse by creating a BFC */
.parent {
display: flow-root; /* Modern BFC trigger */
}💡Vertical margin collapse between siblings and BFC prevention.
🎯 Interview Key Takeaway
Vertical margins collapse between block siblings. Use display: flow-root, flex, or grid to prevent it.
#Margin#Collapse#Layout#Beginner
Back to all CSS & Modern Layouts Questions→