How do I center a div? (the definitive 2026 answer)

asked 3 months ago93 viewsen

5

I know it's a meme, but I genuinely keep forgetting. Horizontally, vertically, both. What's the modern way?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 3 months ago

1 Answer

6
✓
✓ Accepted answer

Both axes, inside a parent:

.parent { display: grid; place-items: center; }

Flexbox equivalent:

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

Horizontally only, block element with a width:

.box { max-width: 600px; margin-inline: auto; }

Inline or text content: text-align: center; on the parent.

Over everything (modal):

.modal { position: fixed; inset: 0; margin: auto; width: fit-content; height: fit-content; }

For vertical centering, remember the parent needs a height (e.g. min-height: 100dvh for a full screen). dvh accounts for mobile browser toolbars, unlike vh.

Sign in to tell others whether this worked.

answered 3 months ago

Sign in and verify your email to post an answer.