Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.5 — Centering Anything
CSS · Example 3 of 3

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.

01

Centre a 320px-wide .login card horizontally on the page, with 40px of space above it.

02

Centre an <h1> both ways in a full-screen .splash section.

03

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

01

How would you centre a block horizontally, and why does it need a width?

02

Show two ways to centre an element both horizontally and vertically, and say when you'd choose each.

03

Why doesn't margin: auto centre vertically in normal flow, but does in a flex container?

04

Explain how top: 50%; left: 50%; transform: translate(-50%, -50%) centres a box.

Safe centring: when the child is bigger than the parent

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

center child left: -50
auto child left: 0