Auto margins centre a block
The 160px of leftover space is split in two when both sides are auto, and all goes to one side when only one is.
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
centred: left gap 80 right gap 80
pushed right: left gap 160 right gap 0