Command Palette

Search for a command to run...

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

Six ways to centre a box, measured

A 60×40 box in a 200×100 parent is centred when it is 70px from the left and 30px from the top. Five methods get both. margin-inline: auto in normal flow only centres horizontally: vertical auto margins count as zero in block layout.

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.

Six ways to centre a box, measured

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

flex       left 70 top 30
grid       left 70 top 30
flexauto   left 70 top 30
abs        left 70 top 30
translate  left 70 top 30
block      left 70 top 0