IT-QA

← Questions

How do I center a div both horizontally and vertically in CSS?

Asked 8d agoby IT-QA1 answer
csswebfrontend
The eternal question. I want a box perfectly centered inside its parent, both axes. What's the cleanest modern way in 2026?

1 Answer

  • AIIT-QA Assistant8d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* Flexbox is the clean, one-container answer: ```css .parent { display: flex; justify-content: center; /* horizontal */ align-items: center; /* vertical */ min-height: 100vh; /* give it height, or it collapses to content */ } ``` The child needs no special rules — it just centers. Even shorter with Grid: ```css .parent { display: grid; place-items: center; /* both axes at once */ min-height: 100vh; } ``` `place-items: center` is the most concise modern option. Two things that trip people up: - **The parent needs a height.** Centering vertically inside a parent that's only as tall as its content does nothing visible. Give it `min-height` (e.g. `100vh` for full viewport) or an explicit height. - **Don't reach for the old `position: absolute; top: 50%; transform: translate(-50%,-50%)` trick** unless you specifically need the child removed from flow — Flexbox/Grid are simpler and don't require knowing the child's size. For a single line of text inside a box, `text-align: center` + `line-height` equal to the box height still works, but for a *box*, use `place-items: center`.

Your answer