Flexbox and Grid
Center content deliberately
Choose the correct Flexbox, Grid, margin, or text-alignment utility based on what you are centering and along which axis.
“Center this” sounds like one operation. In CSS it’s at least five, depending on what you’re centering and on which axis.
The simplest way to center one child on both axes is Grid:
<div class="grid min-h-screen place-items-center">...</div>
place-items-center centers every grid item horizontally and vertically in its cell. min-h-screen makes the container at least as tall as the viewport. On mobile, min-h-dvh tracks the visible area more accurately, because browser bars come and go.
Pick the right tool
Before writing a class, identify the box and the axis:
- center a block horizontally:
mx-auto max-w-xl - center text inside its box:
text-center - center flex children on both axes:
flex items-center justify-center - center one grid item in its cell:
place-self-center - center all grid items in their cells:
place-items-center
Flexbox axes again
In a flex row, items-center centers vertically and justify-center horizontally. With flex-col they swap: justify-center is now vertical and items-center horizontal. If your centering looks wrong after changing direction, this is why.
Two things that don’t work
mx-auto needs leftover space to distribute. A block with w-full already fills its container, so the automatic margins have nothing to do. Add a max-w-* and it works.
text-center centers the inline content, the text and inline elements. It doesn’t move the paragraph box itself. To center the box, use mx-auto on it.
Centering and overflow
A sign-in card centered in a fixed-height container pushes content off screen when the form grows. Prefer a minimum height plus padding, so the layout can expand and scroll:
<main class="grid min-h-dvh place-items-center p-6">
<form class="w-full max-w-md">...</form>
</main>
The form fills the width up to max-w-md, stays centered, and when it gets taller than the viewport the page just scrolls. With h-dvh instead of min-h-dvh, the bottom of the form would be cut off.
Don’t center by reflex. A centered container is fine, but the text inside long paragraphs and forms is easier to read left-aligned. Try this: center a form box while keeping its labels left-aligned. Test a short form and a very tall one at 200% zoom, and explain why min-h-dvh plus padding beats a fixed height.
Lesson completed