Margin collapsing, measured
In the plain parent, the blue background starts right at the child: the child's 20px margin collapsed with the parent's 10px and escaped above it.
Margins can be auto (to centre a block), negative (to pull boxes closer or overlap them), and vertical margins between blocks collapse into one, which explains most mystery gaps in CSS.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Centre a .notice that is at most 500px wide in its parent, then log the computed margin-left when the parent is 700px wide.
Two paragraphs: the first has margin-bottom: 24px, the second margin-top: -8px. Both are 30px tall blocks. Log the gap between them.
Fix a .card whose first child h2 margin escapes, without changing the h2. Log the distance from the card's top to the h2's top.
Explain it without notes
What is margin collapsing and when does it happen?
Why does margin: 0 auto centre a block, and what does it need to work?
A child's top margin shows up above its parent's background. Why, and what are three ways to fix it?
Give two legitimate uses of negative margins and one risk.
In which situations do margins never collapse?
Preview
Console
Nothing logged yet.Expected console output
gap between A and B: 30
plain parent: child sits 0 px below the parent's top
flow-root parent: child sits 20 px below the parent's top