# Margin Collapsing

> The Margin Collapsing in CSS is the behavior where the vertical margins of adjacent block-level elements merge into a single margin.

## Why do vertical margins collapse in CSS and how do I prevent it?

The behavior where vertical margins of adjacent block-level elements collapse into a single margin. This occurs when two or more block elements have vertical margins that touch each other, resulting in only the largest margin being applied.

- Topic: Layout Concepts
- Type: concept

## Example

Wrong:

```css
.card {
  background: #eee;
}
.card h2 {
  margin-top: 24px;
}
```

Right:

```css
.card {
  background: #eee;
  display: flow-root;
}
.card h2 {
  margin-top: 24px;
}
```

`display: flow-root` stops the child margin from escaping the parent, so the space appears inside the card.

## Common mistakes

- Adding `margin-top` to the first child and seeing the whole parent move down instead.
- Expecting two 20px margins between siblings to add up to 40px.

## Interview questions

### Do margins collapse in flexbox or grid?

No. Margins of flex items and grid items never collapse with each other or with their container.

### Do horizontal margins collapse?

No. In horizontal writing modes only vertical (block-direction) margins collapse.

### Which margin wins when margins collapse?

The larger margin wins. If one is negative, the result is the largest positive margin plus the most negative one.

## Related cards

- [Block Formatting Context](https://wonderium.dev/html/block-formatting-context.md)
- [Document Flow](https://wonderium.dev/html/document-flow.md)
- [margin](https://wonderium.dev/css/margin.md)
- [gap](https://wonderium.dev/css/gap.md)
- [padding](https://wonderium.dev/css/padding.md)

---

- Level: [HTML](https://wonderium.dev/html.md)
- HTML version: https://wonderium.dev/html/margin-collapsing
- Last updated: 2026-11-25
