Command Palette

Search for a command to run...

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

Centring text and inline content

text-align: center centres the heading, the paragraph and the inline-block button, because they are all lines of inline content inside the banner. Make the pill's text long enough to wrap and watch the line-height trick fall apart: each line is 40px tall.

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.

Centring text and inline content

Preview

Press Run to see the page.

Console

Nothing logged yet.