Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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.

  • Intermediate
  • 25 minutes
  • Examples run with Node.js 24.21.0 and quickjs 0.32.0
  • By MySmartCoPilot
Free core, Pro depth: 7 of 25 minutes free
Free: Combine the largest positive and most negative terms · Check which margin edges are adjoining · Contain margins at the formatting-context boundary · 2 more sections. With a pass: 2 in-depth parts and 3 interview answers, about 18 minutes.

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

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

Predict a collapsed margin JavaScript · collapse.mjs
// 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

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:

Interactive · stage by stage Positive and negative terms decide one collapsed gap Use the horizontal-writing lab. Use the original sibling, mixed-sign and all-negative lists; identify the two terms before adding them.
Positive and negative terms decide one collapsed gap, step 5 of 5. Showing Largest positive (24 px), Most negative (−8 px), Collapsed gap (16 px). In focus: Collapsed gap.Largest positive24 pxMost negative−8 pxCollapsed gap16 px

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

  1. Question 1 of 2 The adjoining margins are 30 px and 20 px, both positive. What gap does the original model give?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 30 px

    The largest positive term is 30 and the negative term starts at zero, giving 30 px rather than 50 px.

  2. Question 2 of 2 The adjoining margins are −10 px and −25 px. What is their collapsed gap?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: -25 px

    The largest positive term is zero. Add the most negative term, −25; a negative result means overlap.

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

In the horizontal-writing lab, adjoining top/bottom block-axis margins collapse in one block formatting context.Horizontal-writing lab:block-axis margins meet:siblings, a parent and its first or last child,or the top and bottom of an empty block1. Are both boxes in normal flow,in the same block formatting context?Last child’s bottom: parent height auto,with zero min-height.Empty block: height auto or zero,with zero min-height.If not, no collapse: use that layout’s spacing rule,such as separate flex-item margin contributions2. Does anything separate them:padding, a border, a line of text or clearance?If so, the margins add up3. They collapse into one margin:the largest positive marginplus the most negative oneyesno

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.

  1. 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.
  2. 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.
  3. 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:

Interactive · stage by stage Check the connection before selecting a gap Use the horizontal-writing lab. Compare siblings, an empty block and a parent edge from the complete twelve-case lab.
Check the connection before selecting a gap, step 5 of 5. Showing Which boxes meet? (flex items), Anything separates? (no separating box), Same layout context? (new boundary at parent), Adjoining or separate (30 + 20 = 50 px). In focus: Which boxes meet?, Adjoining or separate.Which boxes meet?flex itemsAnything separates?no separating boxSame layout context?new boundary at parentAdjoining or separate30 + 20 = 50 px

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

  1. Question 1 of 2 In the horizontal-writing lab, an empty ordinary block has no height, line box, padding or border. What can happen to its block-axis top and bottom margins?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: They can join each other and adjoining margins around it.

    Identify whether anything separates the edges. The original four-margin empty-block fixture is one connected group.

  2. Question 2 of 2 Two ordinary block siblings are inside the same flow-root card. Their adjacent margins are 30 px and 20 px, with no separator. Which result follows?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: They can still collapse to 30 px inside the card.

    An independent BFC prevents margins from crossing its edge, while ordinary adjoining siblings inside it still use margin-collapse rules.

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

Interactive · stage by stage Where the child’s 24 px margin ends up Use the horizontal-writing lab. Advance through plain, padded, flow-root, hidden, clip and size-container parents without changing the child margin.
Where the child’s 24 px margin ends up, step 6 of 6. Showing Parent edge (inline-size container), Child margin (24 px), Outside gap (0 px), Inside offset (24 px). In focus: Parent edge, Inside offset.Parent edgeinline-size containerChild margin24 pxOutside gap0 pxInside offset24 px

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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

  1. Question 1 of 2 Which change contains a heading’s edge margin without adding overflow clipping?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: display: flow-root on the parent.

    Use a formatting-context operation for containment; a paint change or clipping operation alone has another purpose.

  2. Question 2 of 2 The plain parent in the original clip row has no top padding or border, and its first child has a 24 px top margin. How much is inside the parent?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 0 px

    Clip alone does not start the independent context, so this margin can collapse through the edge: 24 px above and zero inside.

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

Interactive · stage by stage Auto margins allocate the space the layout leaves Work from the 800/600 px column and the 120/24 px flex-height fixture.
Auto margins allocate the space the layout leaves, step 4 of 4. Showing Available size (120 px), Item size (24 px), Positive free space (96 px), Auto margin shares (one auto side takes rest). In focus: Auto margin shares.Available size120 pxItem size24 pxPositive free space96 pxAuto margin sharesone auto side takes rest

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. 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.
  2. 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.
  3. 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.
  4. 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

  1. Question 1 of 2 An 800 px horizontal container holds a 600 px column with two inline auto margins. How much unused space goes to each side?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 100 px

    The unused width is 800 − 600 = 200 px. Both auto sides share it, so each gets 100 px.

  2. Question 2 of 2 In the original sole-item flex fixture, the container is 120 px tall and the item 24 px tall. How much does each of its two auto block-axis margins receive?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 48 px

    The positive unused height is 96 px. Two auto margins receive 96 / 2 = 48 px each in this stated fixture.

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

Interactive · stage by stage One parent owns the space between components Use the horizontal-writing lab. Compare the original margin pair with a margin-free 16 px-gap stack and a scoped text-flow reset.
One parent owns the space between components, step 4 of 4. Showing Component margins (one authored later margin), Parent layout (normal text flow), Space between items (16 px), Outer edges (first child starts at edge). In focus: Component margins, Outer edges.Component marginsone authored later marginParent layoutnormal text flowSpace between items16 pxOuter edgesfirst child starts at edge

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. 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.
  2. 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.
  3. 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.
  4. 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

  1. Question 1 of 2 A flex column keeps a 30 px end margin and 20 px start margin between two items, then adds a 16 px gap. What distance do those contributions give?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 66 px

    Flex-item margins do not collapse. Retaining both gives 30 + 20 + 16 = 66 px; gap does not clear them.

  2. Question 2 of 2 The direct children’s block margins are reset before .flow > * + * assigns a top margin. Which child gets no authored top margin from that rule?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The first direct child.

    The reset and the scoped later-child selector form one spacing contract; preserve nested content’s own policy.

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.

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.

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 above is collapse([parent.margin, childMargin]) and inside is 0.
  • The parent starts a new formatting context when its display is 'flow-root', 'flex', 'grid' or 'inline-block', when its overflow is 'hidden', 'auto' or 'scroll' (not 'clip'), or when its containerType is 'inline-size' or 'size'.
  • Otherwise above is the parent's own margin and inside is 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.

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.

  1. Question 1 of 12 A paragraph has margin-bottom: 18px and the heading after it margin-top: 32px. Both are ordinary blocks in normal flow. How many pixels separate them?

    Type a number.

    Show the answer: Question 1 of 12

    Answer: 32 px

    The two margins are adjoining, so they collapse into one: the larger, 32 px. They would add up to 50 px only if something separated them or if the two boxes were flex or grid items.

  2. Question 2 of 12 Three margins meet: 24px, 40px and -16px. What is the collapsed margin?

    Type a number.

    Show the answer: Question 2 of 12

    Answer: 24 px

    The largest positive margin, 40 px, plus the most negative one, −16 px, gives 24 px. The 24 px margin itself plays no part.

  3. Question 3 of 12 A card's first heading has a top margin that leaks out above the card. Which changes to the card keep the margin inside it?

    Choose every answer that is right.

    Show the answer: Question 3 of 12

    Answer:

    • padding-top: 1px
    • display: flow-root
    • display: flex; flex-direction: column

    flow-root and a flex container start a new formatting context, and padding separates the two margins, so each keeps the heading's margin inside the card. overflow: clip clips without starting a formatting context, so the stated plain parent-child margin connection still remains. The card's own margin is not what leaks.

  4. Question 4 of 12 In the horizontal-writing lab, two inline-block badges sit side by side; the first has margin-right: 12px, the second margin-left: 8px. What is the gap between them, not counting any space character?

    Choose one answer.

    Show the answer: Question 4 of 12

    Answer: 20px, because these inline-axis margins do not collapse

    Collapse follows the formatting context’s block axis. The stated horizontal-writing badges keep separate inline-axis margin contributions, giving 12 + 8 = 20 px; physical left/right block margins can collapse in vertical writing. Between inline-blocks a space in the HTML also adds the width of a space character, which is why the question leaves it out.

  5. Question 5 of 12 You add container-type: inline-size to a wrapper so its children can use container queries. What can change in the layout even before any query matches?

    Choose one answer.

    Show the answer: Question 5 of 12

    Answer: Margins of the first and last child stop collapsing through the wrapper, so spacing near it changes.

    A size container establishes an independent formatting context, so its children's margins no longer collapse with its own. For the stated 24 px child-margin fixture, the independent boundary keeps that margin inside rather than above the wrapper. Inline-size containment also stops the wrapper from taking its width from its content.

  6. Question 6 of 12 Which CSS centres a block horizontally in its container?

    Choose one answer.

    Show the answer: Question 6 of 12

    Answer: max-inline-size: 40rem; margin-inline: auto;

    Auto margins on both sides share the space the box does not use, so the box needs a width or a maximum width smaller than its container. Without one it already fills the line and there is nothing to share. Auto top and bottom margins count as 0 in normal flow, and text-align centres the inline content, not the box.

  7. Question 7 of 12 What decides a group of adjoining positive block-axis margins in the horizontal-writing lab?

    Choose one answer.

    Show the answer: Question 7 of 12

    Answer: The largest positive margin.

    First decide whether the margins are adjoining, then combine the largest positive and most negative terms.

  8. Question 8 of 12 The original empty block connects four margins. What change creates an actual separator at its top edge?

    Choose one answer.

    Show the answer: Question 8 of 12

    Answer: A 1 px top border.

    The connection is geometric. A border or padding strip changes it even when the element has no visible text.

  9. Question 9 of 12 What does overflow: clip alone do to the plain parent’s formatting-context boundary?

    Choose one answer.

    Show the answer: Question 9 of 12

    Answer: It does not create an independent formatting context.

    Use an explicit context creator when boundary containment is required; a clipping choice is not a substitute.

  10. Question 10 of 12 Keep a 600 px column with two inline auto margins, but make its horizontal container 700 px wide. What does each margin receive?

    Type a number.

    Show the answer: Question 10 of 12

    Answer: 50 px

    The available surplus is now 700 − 600 = 100 px, shared as 50 px on each side.

  11. Question 11 of 12 Which arrangement gives a parent sole ownership of a 16 px gap between adjacent flex components?

    Choose one answer.

    Show the answer: Question 11 of 12

    Answer: Reset their outer margins and set gap: 16px on the parent.

    Parent-owned spacing requires the components not to contribute competing outer margins.

  12. Question 12 of 12 A flex stack clears both adjacent item margins and uses gap: 16px. How much space does its gap add before the first item?

    Type a number.

    Show the answer: Question 12 of 12

    Answer: 0 px

    Gap separates adjacent items; it does not supply padding or an outer edge gap before the first item.

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.

  1. 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.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. 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.

    Model answer, Pro. First step and follow-ups

  3. 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.

    Model answer, Pro. First step and follow-ups

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

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.