CSS Module 4 – The box model, sizing and overflow
Margin collapse and formatting contexts
Predict adjoining CSS margins, contain parent-child margin boundaries with flow-root, flex or grid, and choose auto margins and parent-owned spacing.
What you will learn
- Predict block-axis margin collapse in the horizontal-writing sibling, parent-child and empty-block fixtures
- Prevent unwanted collapse with display flow-root, padding, borders or a flex or grid parent
- Use auto margins to centre blocks and to push items apart
- Choose a spacing strategy in which parents set the space between components with gap
Before you start
What you’ll learn · Before you start
What you will learn
- Predict block-axis margin collapse in the horizontal-writing sibling, parent-child and empty-block fixtures
- Prevent unwanted collapse with display flow-root, padding, borders or a flex or grid parent
- Use auto margins to centre blocks and to push items apart
- Choose a spacing strategy in which parents set the space between components with gap
Before you start
On this page
margin collapse: The combination of adjoining margins in a formatting context’s block axis, using the largest positive and most negative terms; physical sides depend on writing mode. merges adjoining block-axis margins in normal flow: the lab’s positive 30 px bottom and 20 px top margins leave 30 px, not 50 px. Margin collapse can also move a first child’s margin outside its parent, pushing a heading’s whole card down rather than creating space inside. independent formatting context: A layout environment whose internal layout is separated from the surrounding context; margins do not collapse across its outer boundary. govern layout relationships within a box. Formatting contexts for flex or grid keep item margins separate, while independent boundaries prevent collapse across them. In this horizontal-writing lab, top/bottom margins are block-axis margins; padding, a border or a line box can stop them adjoining.
Use the editable gap model, then inspect all twelve HTML cases.
Combine the largest positive and most negative terms
The margin-collapse rule in CSS 2 fits in one line of code: take the largest positive margin among those that meet, and add the most negative one. If all of them are negative, the most negative wins; if they are all positive, the largest does.
The rule: the largest positive margin plus the most negative one
// Adjoining block-axis margins in the horizontal-writing fixtures combine into one (CSS 2, section 8.3.1):
// the largest positive margin plus the most
// negative one. Edit the lists and run it again to predict a gap before you open DevTools.
function collapse(margins) {
const largestPositive = Math.max(0, ...margins);
const mostNegative = Math.min(0, ...margins);
return largestPositive + mostNegative;
}
const cases = [
['30px below a block, 20px above the next', [30, 20]],
['an empty block between: 10, 20, 30, 10', [10, 20, 30, 10]],
['30px and -10px', [30, -10]],
['-10px and -25px', [-10, -25]],
['h2 24px, its section 16px, a -8px pull', [24, 16, -8]],
];
for (const [label, margins] of cases) {
console.log(`${label.padEnd(42)} -> ${collapse(margins)}px`);
}
// Margins that are not adjoining are simply added: side by side, between flex or grid items, or across padding.
console.log(`${'30px and 20px in a flex column'.padEnd(42)} -> ${30 + 20}px`); Output
30px below a block, 20px above the next -> 30px an empty block between: 10, 20, 30, 10 -> 30px 30px and -10px -> 20px -10px and -25px -> -25px h2 24px, its section 16px, a -8px pull -> 16px 30px and 20px in a flex column -> 50px
Recorded with Node.js 24.21.0 on macOS 26 arm64. To run it yourself: mise exec node@24.21.0 -- node collapse.mjs
Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs.
Your run, in this browser
The rule exists for text. The HTML standard gives every paragraph margin-block: 1em, and because the margins
collapse, two paragraphs in a row are 1em apart, not 2em. Margins of the root element never collapse, and the inline-axis left/right margins of this horizontal-writing context do not collapse.
Compare the original sibling and signed groups before each reveal:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- Two positive margins. For [30, 20], the largest positive is 30 and there is no negative term, so the latter starts at zero. The collapsed gap is 30 px, not their sum.
- An empty block joins them. The original empty-block list [10, 20, 30, 10] has the same largest positive term, 30 px. All four adjoining margins still produce one 30 px gap.
- Mix the signs. For [30, −10], add the largest positive 30 to the most negative −10. The result is 20 px; choosing only the positive maximum would miss the pull.
- Keep a negative overlap. For [−10, −25], the positive term is zero and the negative term is −25. The gap is −25 px, which means overlap rather than a positive space.
- A joined three-term case. The original [24, 16, −8] list combines 24 and −8 to give 16 px. The smaller positive 16 is not an extra addition.
The −25 px result is an overlap, not an error to clamp to zero.
Checkpoint
Check: The signed collapsed-gap formula
Check which margin edges are adjoining
A 30 px bottom margin and a 20 px top margin collapse only when they are adjoining in ordinary block flow. Siblings can meet; a parent’s edge can meet its first or last child; an empty block can connect both sides. Padding, a border, a line box or clearance may interrupt that connection.
Collapse follows the containing formatting context’s block axis. In vertical-rl, adjoining physical left/right margins can collapse instead; the inline-axis top/bottom margins do not. Use the overview for the unchanged horizontal-writing lab:
Where margins meet
Two questions decide whether two margins collapse
Text description of the diagram
The diagram is a column of steps that starts where the horizontal-writing lab’s top/bottom block-axis margins meet: two siblings, a parent and its first or last child, or the top and bottom of an empty block.
- The first question checks normal flow, the shared block formatting context and the height conditions for the relevant edges. A last child's bottom margin can collapse with its parent's bottom margin when the parent's height is auto and its min-height is zero. An empty block can collapse its own top and bottom margins when its height is auto or zero and its min-height is zero, with no in-flow content or separators. If these conditions do not hold, the margins do not collapse; use the actual layout’s spacing rules rather than assuming every pair of out-of-flow boxes has an additive gap. Flex and grid items use separate margin contributions, and margins cannot collapse across a flow-root boundary. Ordinary block siblings inside that new context can still have adjoining margins.
- If they are, the second question asks whether padding, a border, a line of text or clearance separates the margins. If something does, they add up too.
- If nothing does, the margins collapse into one margin: the largest positive margin plus the most negative one.
Compare the lab’s sibling and parent arrangements:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- Ordinary block siblings. The sibling pair has 30 px below the first block and 20 px above the second. They meet in one block formatting context with nothing separating them, so they collapse.
- The empty block connects. The empty middle block has no border, padding, height or line box. Its 20 px and 30 px margins join the neighbouring 10 px margins, yielding the lab’s 30 px group.
- An unseparated parent edge. The plain parent has no top padding or border. Its first child’s 24 px top margin can collapse through that edge, leaving 24 px above the parent and zero inside.
- An independent outer edge. A flow-root boundary stops that parent-child connection. It does not prevent two ordinary block siblings within the new BFC from collapsing with each other.
- Flex items use another rule. The flex-column lab makes the two boxes flex items. Their 30 px and 20 px margins do not collapse together, so this gap is 50 px.
Context boundaries contain edges without resetting adjoining siblings inside.
Checkpoint
Check: Which margin edges can meet
Contain margins at the formatting-context boundary
A parent’s independent formatting context keeps a child’s margin from collapsing through that parent’s edge.
flow-root creates a block formatting context. It contains floats and edge margins without overflow clipping. Flex establishes flex layout. Its items’ margins do not collapse. Grid establishes grid layout. Its items also keep separate margins.
Other creators have other jobs: inline-block is atomic; floats and absolute or fixed boxes leave normal flow; hidden, auto and scroll change overflow. container-type: inline-size or size excludes content from the contained sizing axis; contain: layout, paint, content or strict adds its containment. clip clips without creating this boundary.
Compare the child’s 24 px margin across the same parent cases:
What stops margins from collapsing
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- The plain parent. The first child has a 24 px top margin and no separator stops it meeting the plain parent’s edge. It appears above the parent, with zero offset inside.
- One pixel separates. Add 1 px of top padding. The margins no longer meet; the child begins 1 + 24 = 25 px inside the parent, and no child margin escapes above it.
- flow-root contains the edge. With flow-root instead of padding, a new block formatting context contains the child’s margin. There is no extra strip to add, so the inside offset is 24 px.
- hidden also changes overflow. Overflow: hidden similarly establishes the boundary on this block, keeping 24 px inside. It also clips content and makes a scroll container, unlike flow-root alone.
- clip leaves the connection. Overflow: clip alone does not create that formatting context. The child margin can collapse through the plain parent edge again: 24 px above and zero inside.
- A size container is a boundary. Container-type: inline-size establishes an independent formatting context and inline-size containment. The margin is kept 24 px inside even before any container query matches.
Containment does not add a separating strip.
Checkpoint
Check: A context contains its outer edge
Auto margins allocate the space a layout leaves
An 800 px horizontal container and a 600 px column leave 200 px unused. Two inline auto margins share it as 100 px each. In the stated horizontal-writing normal block flow, auto top/bottom block-axis margins are zero, so they do not centre the box vertically.
Flex instead gives positive free space to auto margins before alignment. One auto start margin can push the account link to the end. Two auto margins can centre the sole item: the 120 px container and 24 px item leave 48 px above and below.
Compare those allocations:
Auto margins: centring and pushing apart
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- The column leaves 200 px. An 800 px horizontal container and a 600 px column leave 200 px unused. Two inline auto margins divide it equally, giving 100 px on each side.
- Block auto is not vertical. In this horizontal-writing block flow, auto top and bottom margins have used value zero. A 200 px-wide note is not vertically centred merely by margin: auto.
- The flex fixture has 96 px. The sole 24 px-tall item in the 120 px flex container leaves 96 px. Its two auto block-axis margins receive 48 px each in this fixture.
- One side can take the rest. The navigation fixture gives its last link an auto start margin. That margin takes the remaining positive main-axis space before justify-content can distribute it.
Only positive surplus is shared.
Checkpoint
Check: Auto margins allocate unused space
Let the parent own component spacing
A component should not need to know its predecessor’s content to set its spacing. The parent can own that distance: with item margins reset, the stated flex or grid gap: 16px gives 16 px between neighbours with no extra distributed alignment and no outer gap. Retained margins add extra space.
For normal text flow, reset direct children’s block margins, then use .flow > * + * to assign one top margin to each later child. The first child keeps no outer top margin. margin-trim trims container-edge margins instead; check target-browser support before relying on it.
Compare the two policies:
A spacing strategy that avoids surprises
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- The normal-flow margin pair. A 30 px end margin and 20 px start margin collapse to 30 px for adjoining ordinary blocks. The components own those two declarations.
- Flex keeps both margins. Making the parent a flex column changes the relation. If the margins remain, they add to 50 px; the new layout has not reset either component’s margin.
- Reset before using gap. For parent-owned spacing, clear those outer margins and set gap: 16px. The stack then has 16 px between adjacent items and no gap before the first or after the last.
- Keep text flow scoped. The text-flow rule first clears direct-child block margins, then applies margin-block-start: 1em to every child after the first. Nested article or list margins remain their own concern.
The parent’s explicit gap replaces competing outer component margins.
Checkpoint
Check: The parent owns the spacing contract
Trace all twelve cases and choose a containment fix Pro: opens with a Pro, Premium or Ultimate pass
Trace every original margin case.
In this part:
- Where adjoining margins meet in the complete lab
- Which changes contain the heading’s margin
- flow-root contains floats and margins without clipping
- Diagnose the boundary before changing its arithmetic
- Margin collapse follows the formatting-context block axis
2 runnable examples (CSS, HTML) · about 7 minutes
Opening this part with your pass…
This part opens with any MySmartCoPilot pass.
- Pro pass · 1 week₹79$2.99
- 30 days₹179$5.99
- 1 year₹1,699$45
One payment; nothing renews unless you choose to. The price shown is the total you pay: no fees or charges are added at checkout.
Passes can’t be bought right now, so this part can’t be opened at the moment. The free part above stands on its own. If you have a pass, enter your licence key.
It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).
Apply auto margins and an explicit spacing contract Pro: opens with a Pro, Premium or Ultimate pass
Choose the intended spacing contract.
In this part:
- Auto margins in the complete block and flex fixture
- Keep container gaps and text flow explicit
- Distinguish a BFC from a spacing reset
- Key takeaways from the complete margin cases
2 runnable examples (CSS, HTML) · about 5 minutes
Opening this part with your pass…
This part opens with any MySmartCoPilot pass.
- Pro pass · 1 week₹79$2.99
- 30 days₹179$5.99
- 1 year₹1,699$45
One payment; nothing renews unless you choose to. The price shown is the total you pay: no fees or charges are added at checkout.
Passes can’t be bought right now, so this part can’t be opened at the moment. The free part above stands on its own. If you have a pass, enter your licence key.
It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).
Practise: predict the gap
The exercise turns the rules of this lesson into two functions, and its tests include the cases of the lab.
Exercise · Medium · JavaScript
Predict where a heading's top margin ends up
A card whose heading has a top margin can show that space inside the card, or above it, where it pushes the whole card down. Write two functions in gaps.mjs that predict it, and export them. All lengths are in px.
The first function, collapse(margins), returns the single margin that a list of adjoining block-axis margins in this horizontal-writing fixture becomes: the largest positive margin plus the most negative one. collapse([30, -10]) is 20, collapse([-10, -25]) is -25, and an empty list gives 0.
The second, childStart({ parent, childMargin }), describes a parent block and the top margin of its first child, and returns { above, inside }: how far the parent's border box starts below the block before it (which has no margin of its own), and how far below the parent's border-box top the child's border box starts. parent may leave out any of these, which then have the values in brackets: margin (its own top margin, 0), paddingTop (0), borderTop (0), display ('block'), overflow ('visible') and containerType ('normal').
- The two margins collapse when nothing separates them, that is with no top padding and no top border, and when the parent does not start a new formatting context. Then
aboveiscollapse([parent.margin, childMargin])andinsideis0. - The parent starts a new formatting context when its
displayis'flow-root','flex','grid'or'inline-block', when itsoverflowis'hidden','auto'or'scroll'(not'clip'), or when itscontainerTypeis'inline-size'or'size'. - Otherwise
aboveis the parent's own margin andinsideis the border, the padding and the child's margin added.
The sample tests import both functions from gaps.mjs and run in your browser; several of them are the cases of the lesson’s complete lab. This numerical model assumes horizontal ordinary block children, no intervening line box or clearance, and the listed parent properties; it does not measure DOM geometry.
Starter code · gaps.mjs
/** The one margin that adjoining block-axis margins in the horizontal-writing fixture collapse into (px). */
export function collapse(margins) {
// Replace this line with your code.
return 0;
}
/** Where a first child's top margin ends up: { above, inside } (px). */
export function childStart({ parent, childMargin }) {
// Replace this line with your code.
return { above: 0, inside: childMargin };
} The sample tests · gaps.test.mjs
import { test, assert } from 'mysmartcopilot:test';
import { collapse, childStart } from './gaps.mjs';
test('the largest positive margin wins', () => {
assert.equal(collapse([30, 20]), 30);
assert.equal(collapse([10, 20, 30, 10]), 30);
});
test('negative margins are taken off, and all-negative lists keep the most negative', () => {
assert.equal(collapse([30, -10]), 20);
assert.equal(collapse([24, 16, -8]), 16);
assert.equal(collapse([-10, -25]), -25);
assert.equal(collapse([-5]), -5);
});
test('no margins, or only zeros, make 0', () => {
assert.equal(collapse([]), 0);
assert.equal(collapse([0, 0]), 0);
});
test('a plain parent lets the child margin out (the lab: 24px above, 0 inside)', () => {
assert.deepEqual(childStart({ parent: {}, childMargin: 24 }), { above: 24, inside: 0 });
assert.deepEqual(childStart({ parent: { display: 'block', overflow: 'visible' }, childMargin: 24 }), { above: 24, inside: 0 });
});
test("the parent's own margin collapses with the child's", () => {
assert.deepEqual(childStart({ parent: { margin: 16 }, childMargin: 24 }), { above: 24, inside: 0 });
assert.deepEqual(childStart({ parent: { margin: 32 }, childMargin: 24 }), { above: 32, inside: 0 });
assert.deepEqual(childStart({ parent: { margin: 16 }, childMargin: -8 }), { above: 8, inside: 0 });
});
test('padding or a border keeps the margin inside (the lab: 1px of padding gives 25px)', () => {
assert.deepEqual(childStart({ parent: { paddingTop: 1 }, childMargin: 24 }), { above: 0, inside: 25 });
assert.deepEqual(childStart({ parent: { borderTop: 2 }, childMargin: 24 }), { above: 0, inside: 26 });
assert.deepEqual(childStart({ parent: { margin: 16, paddingTop: 8, borderTop: 1 }, childMargin: 24 }), { above: 16, inside: 33 });
});
test('flow-root, flex, grid and inline-block start a new formatting context', () => {
for (const display of ['flow-root', 'flex', 'grid', 'inline-block']) {
assert.deepEqual(childStart({ parent: { display }, childMargin: 24 }), { above: 0, inside: 24 }, display);
}
assert.deepEqual(childStart({ parent: { display: 'flow-root', margin: 10 }, childMargin: 24 }), { above: 10, inside: 24 });
});
test('overflow hidden, auto and scroll do too, but clip does not', () => {
for (const overflow of ['hidden', 'auto', 'scroll']) {
assert.deepEqual(childStart({ parent: { overflow }, childMargin: 24 }), { above: 0, inside: 24 }, overflow);
}
assert.deepEqual(childStart({ parent: { overflow: 'clip' }, childMargin: 24 }), { above: 24, inside: 0 });
});
test('a size container is a new formatting context', () => {
assert.deepEqual(childStart({ parent: { containerType: 'inline-size' }, childMargin: 24 }), { above: 0, inside: 24 });
assert.deepEqual(childStart({ parent: { containerType: 'size' }, childMargin: 24 }), { above: 0, inside: 24 });
assert.deepEqual(childStart({ parent: { containerType: 'normal' }, childMargin: 24 }), { above: 24, inside: 0 });
}); A hint
For collapse, keep two running values that start at 0: the largest margin and the smallest one. The answer is their sum, so [30, -10] gives 30 + (−10). For childStart, first decide with one boolean whether the margins can touch: no top padding, no top border, and none of the listed values that start a formatting context.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (QuickJS): nothing is sent to mysmartcopilot.com. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Practice that adapts to you
Practise this lesson
12 questions about 5 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Fresher · What is margin collapsing, and can physical horizontal margins collapse in a vertical-writing context?
Adjoining block-axis margins collapse in normal block flow: combine the largest positive and most negative terms. Thus 30 px with 20 px gives 30 px, and 30 px with −10 px gives 20 px. Physical left/right margins can collapse in vertical writing. In this horizontal lab they stay separate, leaving 30 + 20 = 50 px. Siblings, parent/child edges and empty blocks need an adjoining connection; separating padding, borders, lines and independent formatting-context boundaries prevent it.
-
Fresher to mid
A promo banner has a background colour and no padding, and its heading has margin-top: 24px. On the home page the space shows above the banner, outside its background, but in the product grid the same banner looks right. Explain both, and give two fixes with their trade-offs.
-
Mid to senior
After you add container-type: inline-size to the main content wrapper so its components can use container queries, the gap between the last paragraph and the footer grows from 40 px to 64 px, and a filter panel made a container too shrinks to zero width. Explain both, and fix them without dropping container queries.
-
Fresher to senior
A card becomes flow-root, but two ordinary paragraphs inside it still have a 40 px gap despite 40 px and 24 px adjoining margins. Explain why the gap is not 64 px, then choose a stable component-spacing policy.
Key takeaways
- Decide whether margins are adjoining before combining their positive and negative terms.
- A boundary does not reset its contents.
- Give component gaps to their parent, and use auto margins only when the chosen layout supplies unused space.
Terms in this lesson
- independent formatting context
- A layout environment whose internal layout is separated from the surrounding context; margins do not collapse across its outer boundary.
- margin collapse
- The combination of adjoining margins in a formatting context’s block axis, using the largest positive and most negative terms; physical sides depend on writing mode.
Corrections
- Separated collapse across a boundary from collapse inside one; clarified model, containment and compatibility assumptions.
References
- CSS 2: collapsing margins (W3C CSS Working Group)
- CSS 2: block formatting contexts (W3C CSS Working Group)
- CSS 2: block-level, non-replaced elements in normal flow (auto margins) (W3C CSS Working Group)
- CSS Display Module Level 3: independent formatting contexts and flow-root (W3C CSS Working Group)
- CSS Overflow Module Level 3: the clip value (W3C CSS Working Group)
- CSS Conditional Rules Module Level 5: the container-type property (W3C CSS Working Group)
- CSS Containment Module Level 3: inline-size containment (W3C CSS Working Group)
- CSS Containment Module Level 2: layout and paint containment (W3C CSS Working Group)
- CSS Flexible Box Layout Module Level 1: flex item margins and auto margins (W3C CSS Working Group)
- CSS Box Alignment Module Level 3: gaps between boxes (W3C CSS Working Group)
- CSS Box Model Module Level 4: the margin-trim property (W3C CSS Working Group)
- HTML Standard: rendering, the default margins of paragraphs and the body (WHATWG)
- Mastering margin collapsing (MDN Web Docs) (Mozilla)
- Block formatting context (MDN Web Docs) (Mozilla)
- CSS Gaps: spacing between boxes (W3C CSS Working Group)
- MDN browser compatibility data: margin-trim (MDN Web Docs contributors)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress