How do I center a div? (the definitive 2026 answer)
posée 3 months ago96 vuesen
5
I know it's a meme, but I genuinely keep forgetting. Horizontally, vertically, both. What's the modern way?
Diagnostic IA
Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.
posée 3 months ago
Fabienne Dorval 2.8k
1 réponse
6
✓✓ Réponse acceptée
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.
Connectez-vous pour dire si ça a marché.
answered 3 months ago
Stéphanie Louis 2.9k
Sign in and verify your email to post an answer.