'How do I center a div' is a running joke precisely because CSS gives you five ways and no obvious default. Here's each one and, more usefully, when to pick it.
Both axes — Flexbox (the everyday answer)
flex-center.css
css
.parent {
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal */
}This is the one to reach for 90% of the time. Three lines, works for one child or many, no magic numbers.
Both axes — Grid (even shorter)
grid-center.css
css
.parent {
display: grid;
place-items: center; /* centers on both axes in one line */
}Horizontal only — margin auto
margin-auto.css
css
.child {
width: 40rem; /* needs a defined width */
margin-inline: auto; /* classic block centering */
}Absolute positioning — for overlays
absolute-center.css
css
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}Use this when the element is out of flow — a modal, a badge over an image, a tooltip.
Which one?
- Centering content inside a container → Flexbox (or Grid's place-items).
- Centering a fixed-width block horizontally → margin-inline: auto.
- Centering an overlay that's position:absolute/fixed → the transform trick.
- Centering a whole page's content → Grid place-items on a min-height:100vh wrapper.
There's no single 'correct' way — there's the right tool for the layout. Default to Flexbox, keep Grid's place-items for the shortest version, and the transform trick for overlays.