Don't overlook the viewport-centering use case (e.g., a modal). The new CSS way:
.modal {
position: fixed;
inset: 0;
margin: auto;
width: fit-content;
height: fit-content;
}
No transform hacks needed. Works in all modern browsers.
asked 6 months ago
3
22.1K
Yes, I know this is a classic meme, but seriously — there are now 10 different ways to center a div and I don't know which is best in each context.
I want to understand: when to use margin: auto, Flexbox, Grid, position: absolute with transform, and the new place-items: center shorthand. What's the decision tree?
Don't overlook the viewport-centering use case (e.g., a modal). The new CSS way:
.modal {
position: fixed;
inset: 0;
margin: auto;
width: fit-content;
height: fit-content;
}
No transform hacks needed. Works in all modern browsers.
72
2
Historical note for context: the position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) hack predates Flexbox and is unnecessary in new code. You might still see it in older codebases — just replace it with Flexbox or Grid.
Here's your decision tree in 2024:
Center a block element horizontally within its parent (block context):
.element { margin: 0 auto; width: fit-content; }
Center anything (both axes) in a flex container:
.parent { display: flex; align-items: center; justify-content: center; }
Center in a grid container (cleanest modern syntax):
.parent { display: grid; place-items: center; }
Center absolutely positioned element:
.parent { position: relative; }
.child { position: absolute; inset: 0; margin: auto; }
My default in 2024: Grid + place-items: center for full-screen centering, Flexbox when you also need to control direction/wrapping of multiple children.
1
37
4
22
0