Safe centring: when the child is bigger than the parent
With justify-content: center, the 300px child overflows equally on both sides, so its first 50px sit at a negative position that the scrollbar can't reach. Auto margins never go negative, so margin: auto falls back to the start edge and all the content can be scrolled to. The safe keyword (justify-content: safe center) asks for the same behaviour.
Pick the centering method by what you're centering: text-align: center for text and inline content, margin-inline: auto for a block with a width, place-items: center (Grid) or justify-content plus align-items (Flexbox) for both directions, and inset: 0; margin: auto or translate(-50%, -50%) for positioned boxes.
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 320px-wide .login card horizontally on the page, with 40px of space above it.
Centre an <h1> both ways in a full-screen .splash section.
Put a .play button exactly in the centre of a .video box whose size you don't know, on top of the video.
Explain it without notes
How would you centre a block horizontally, and why does it need a width?
Show two ways to centre an element both horizontally and vertically, and say when you'd choose each.
Why doesn't margin: auto centre vertically in normal flow, but does in a flex container?
Explain how top: 50%; left: 50%; transform: translate(-50%, -50%) centres a box.
Preview
Console
Nothing logged yet.Expected console output
center child left: -50
auto child left: 0