Learn when and why vertical margins collapse in CSS, how to prevent it, and how to control content overflow with the overflow property.
Margin collapse is one of the most confusing behaviors in CSS. It occurs when the vertical margins of adjacent block-level elements overlap, and instead of adding together, only the larger margin is applied.
Adjacent siblings — When two block elements stack vertically, the bottom margin of the first and the top margin of the second collapse into a single margin equal to the larger of the two.
Parent and first/last child — If a parent has no border, padding, or inline content separating it from its child, the child's top margin will collapse with the parent's top margin (and similarly for bottom margins).
Empty blocks — If a block element has no content, padding, border, or height, its top and bottom margins collapse with each other.
overflow set to anything other than visible create a new Block Formatting Context (BFC) and prevent margin collapse with children.<style>
.box {
background-color: #e0e0e0;
padding: 16px;
}
.box-a {
margin-bottom: 30px;
}
.box-b {
margin-top: 20px;
}
/* The gap between A and B is 30px, not 50px.
The margins collapse to the larger value. */
/* Fix: Add overflow: auto to the parent to create a BFC */
.no-collapse {
overflow: auto;
}
</style>
<div class="box box-a">Box A (margin-bottom: 30px)</div>
<div class="box box-b">Box B (margin-top: 20px)</div>
<p>The gap above is 30px, not 50px — margins collapsed.</p>The overflow property controls what happens when content is too large for its container.
| Value | Behavior |
|---|---|
visible | Default. Content overflows the box and is visible outside it. |
hidden | Content is clipped at the box boundary. No scrollbar. |
scroll | Content is clipped, but scrollbars are always shown (even if not needed). |
auto | Content is clipped if needed, and scrollbars appear only when necessary. |
You can also control each axis independently with overflow-x and overflow-y.
The text-overflow property handles how overflowed inline text is signaled to the user. The most useful value is ellipsis, which shows ... when text is truncated:
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}All three properties are required for the ellipsis to work: white-space: nowrap prevents wrapping, overflow: hidden clips the content, and text-overflow: ellipsis adds the dots.
Two sibling divs have margin-bottom: 40px and margin-top: 25px respectively. What is the actual gap between them?