How to Center a Div in CSS (All the Ways)

Center an element horizontally, vertically, or both using Flexbox, Grid, margin auto, or absolute positioning — with the tradeoffs of each approach.

Published September 21, 2026

The modern way to centre a div both ways is display: grid; place-items: center on the parent, or display: flex with justify-content and align-items set to center.

The concept

Centring depends on the axis: horizontally for block elements use margin: 0 auto with a width; vertically needs flex, grid or positioning.

Grid's place-items: center is the shortest; flex is the most familiar. Absolute positioning with transform works when you cannot change the parent's display.

Centred with Grid

┌─────────────────────┐
│ │
│ ┌─────┐ │
│ │ div │ │
│ └─────┘ │
└─────────────────────┘

Practical examples

Grid

.parent { display: grid; place-items: center; min-height: 100vh; }

Flexbox

.parent { display: flex; justify-content: center; align-items: center; }

Horizontal only

.box { width: 300px; margin: 0 auto; }

Absolute + transform

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

Common mistakes

  • Vertical centring without giving the parent a height.
  • Using margin: auto vertically in non-flex blocks.
  • Centring text with the box instead of text-align: center.

Key takeaways

  • Grid: place-items: center.
  • Flex: justify-content + align-items.
  • Parent needs height for vertical centring.

FAQ

How do I centre text?

Use text-align: center on the container.

Does margin: auto centre in flex?

Yes, auto margins absorb free space on both axes inside a flex container.

More CSS articles