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
Centring a block horizontally
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
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
Flexbox is the better choice when several items should be centred together in a row.
Centring with auto margins inside flex or grid
Inside a flex or grid container, margin: auto absorbs space on all sides, centring the item in both directions.
Centring an overlay: absolute positioning
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
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
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?
| Goal | Method |
|---|---|
| Centre text or inline elements | text-align: center |
| Centre a block horizontally | margin-inline: auto with a width |
| Centre one thing in both directions | display: grid; place-items: center |
| Centre a group of items in a row | Flexbox with justify-content + align-items |
| Centre on top of other content | Absolute positioning + translate |
| Centre icon and text in a button | inline-flex + align-items: center |