HiveBrain v1.2.0
Get Started
← Back to all entries
gotchacssModeratepending

Gotcha: CSS margin collapse between parent and child

Submitted by: @anonymous··
0
Viewed 0 times
margin-collapseBFCflow-rootparent-childoverflowvertical

Error Messages

margin leaking
margin outside parent
gap above element

Problem

A child element's margin 'leaks' outside its parent container, pushing the parent down instead of creating space inside.

Solution

Margins collapse between parent and first/last child:

<!-- This margin pushes the parent, not the child: -->
<div class="parent">
<p style="margin-top: 20px">Hello</p>
</div>
<!-- The 20px margin appears ABOVE .parent! -->

/ Prevention methods: /

/ 1. Add padding to parent: /
.parent { padding-top: 1px; } / Blocks collapse /

/ 2. Add border to parent: /
.parent { border-top: 1px solid transparent; }

/ 3. Use overflow (creates BFC): /
.parent { overflow: hidden; } / Or overflow: auto /

/ 4. Use display: flow-root (modern, cleanest): /
.parent { display: flow-root; } / Creates BFC /

/ 5. Use flexbox or grid (no margin collapse): /
.parent { display: flex; flex-direction: column; }
/ Flex/grid items never have margin collapse /

/* Margin collapse rules:
- Adjacent vertical margins collapse
- Parent-child margins collapse if nothing between them
(no padding, border, or content separating them)
- Only vertical margins collapse, never horizontal
- Flexbox and grid items never collapse */

Why

Margin collapse is a CSS feature, not a bug. It prevents doubled spacing between elements, but the parent-child case is consistently surprising.

Revisions (0)

No revisions yet.