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

Centering in CSS has several valid approaches depending on whether you need horizontal, vertical, or both, and whether the element's size is known.

.parent {
  display: flex;
  justify-content: center; /* horizontal */
  align-items: center;     /* vertical */
}

Steps

  1. For both horizontal and vertical centering, set the parent to display: flex with justify-content: center and align-items: center — this is the most broadly recommended modern approach
  2. For horizontal-only centering of a block element with a known width, use margin: 0 auto on the element itself
  3. For centering within CSS Grid, place: place-items: center on the parent achieves the same result as the Flexbox pair above

How it works

Flexbox and Grid centering work regardless of the child's size being known in advance, which is why they've largely replaced older tricks like absolute positioning with negative margins or transforms.

Things to watch for

  • margin: 0 auto only centers horizontally and only works on block-level elements with an explicit width — it does nothing for vertical centering
  • The older position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) trick still works and is occasionally useful when you can't change the parent's display type

FAQ

What's the easiest way to center something both ways today?

display: flex; justify-content: center; align-items: center; on the parent — it works for any child size and is the most widely recommended modern default.

More CSS articles