ShareYourGroupShareYourGroupCSS Lab

How to centre a div in CSS: five methods that work

Each method below was built as a real page and measured in a browser: the box ended exactly in the middle every time.

1. Grid with place-items (the shortest)

.parent { display: grid; place-items: center; min-height: 300px; }

place-items: center centres the child both ways inside its cell. The parent needs a height (here min-height), otherwise it is only as tall as the child and there is nothing to centre in.

2. Flexbox

.parent { display: flex; justify-content: center; align-items: center; min-height: 300px; }

justify-content centres along the row and align-items across it. This is the method most people know, and it works for several children too (they are centred together as a group).

3. Margin auto in a flex container

.parent { display: flex; min-height: 300px; }
.child { margin: auto; }

An auto margin in a flex container takes all the free space on every side, which centres the child. It is useful when only one child should be centred and others should stay at the edges.

4. Absolute position and transform

.parent { position: relative; min-height: 300px; }
.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }

top: 50% and left: 50% put the child's top-left corner at the centre; the translate moves it back by half of its own size. Use it when the child must be taken out of the flow, such as a pop-up.

5. Horizontal only: margin auto with a width, or text-align

.child { width: 320px; margin-inline: auto; }
.parent { text-align: center; }

A block with a set width and automatic side margins sits in the middle of its parent. text-align: center centres inline content such as text, images and inline-blocks.

Which one to pick

For almost every case use the grid method or the flexbox method. Use absolute positioning for overlays. Use margin auto for a page column.

Tested

We built the five examples as one page and measured each child's position in current Chrome and WebKit on 13 November 2026. In each case the centre of the child was within one pixel of the centre of the parent, horizontally and vertically (methods 1 to 4), and horizontally for method 5.

Why is my div centred horizontally but not vertically?

The parent has no height beyond its content. Give it a height or min-height, such as min-height: 100vh for the whole screen.

Does text-align: center centre a block?

It centres the content inside the block, not the block itself. To centre the block use margin auto with a width.

This is an independent site. It is not connected with the W3C, MDN, Google, Apple, Mozilla or Microsoft. Browser and product names belong to their owners.