Centring & Alignment

"How do I centre a div?" used to be the most famous question in CSS. Today there are clear, reliable answers for every situation — text, blocks, elements of unknown size, and things inside flex and grid containers.

Centring text

Try it yourself
Result

Centring a block horizontally

Try it yourself
Result

Auto margins share the leftover space equally. The element needs a width (or max-width) smaller than its container — width: fit-content works for a block that should shrink to its content.

Centring in both directions: grid

Try it yourself
Result

display: grid; place-items: center on the parent is the shortest way to centre a child both horizontally and vertically, whatever its size.

Centring with flexbox

Try it yourself
Result

Flexbox is the better choice when several items should be centred together in a row.

Centring with auto margins inside flex or grid

Try it yourself
Result

Inside a flex or grid container, margin: auto absorbs space on all sides, centring the item in both directions.

Centring an overlay: absolute positioning

Try it yourself
Result

Move the element's top-left corner to the centre, then pull it back by half its own size with translate. Use this when the element must sit on top of other content.

Vertical alignment of a single line

Try it yourself
Result

Turning small components like buttons and badges into inline-flex containers is the easy way to align icons with text.

Alignment in normal block layout

Try it yourself
Result

Recent browsers support align-content on ordinary block containers, so vertically centring content in a fixed-height box no longer requires flex or grid.

Which method should I use?

GoalMethod
Centre text or inline elementstext-align: center
Centre a block horizontallymargin-inline: auto with a width
Centre one thing in both directionsdisplay: grid; place-items: center
Centre a group of items in a rowFlexbox with justify-content + align-items
Centre on top of other contentAbsolute positioning + translate
Centre icon and text in a buttoninline-flex + align-items: center

Try it yourself

Try it yourself
Result