How to center a div with Flexbox (and CSS Grid)

Updated 2026-06-21

To center a div with Flexbox, set the parent to display: flex, then add justify-content: center to center horizontally and align-items: center to center vertically. That single combination centers a child both ways, no matter its size.

The Flexbox way

Flexbox centers along two axes. With flex-direction: row (the default), justify-content controls the horizontal position and align-items controls the vertical position. To perfectly center a child inside a parent:

  1. Give the parent a height so there is room to center into (for a full-screen overlay, min-height: 100vh).
  2. Set display: flex on the parent.
  3. Add justify-content: center and align-items: center.

That is it — the child sits dead center, and it stays centered if its text wraps or its size changes. If you flip to flex-direction: column, the two properties swap roles: justify-content now runs vertically and align-items runs horizontally. Getting them mixed up is the single most common Flexbox mistake.

The CSS Grid way

Grid can do the same thing with less code. On the parent, set display: grid and then place-items: center. That one shorthand centers the child on both axes at once — no separate justify and align needed. Grid is also the better tool the moment you have rows and columns rather than a single line of items: define your tracks with grid-template-columns (for example three equal columns with repeat(3, 1fr)), set a gap, and the browser handles the spacing.

Which one should you reach for?

Both can center. Use whichever matches the rest of the layout you are building.

Stop guessing — see it and copy it

The hard part is rarely the concept; it is remembering which property does what and getting the values right on the first try. That is exactly what a visual playground fixes. In the Flexbox & Grid Playground you toggle direction, justify and align with presets, watch boxes move in real time, then copy the finished rule as plain CSS or Tailwind classes — ready to paste straight into your project.

Because it runs entirely in your browser, nothing you type is uploaded anywhere; the layout updates locally as you drag. It is the fastest way to go from "I need this centered" to working markup without trawling Stack Overflow for the right justify-content value.

Ready to build your layout? Open the Flexbox & Grid Playground, pick a preset, and grab the CSS or Tailwind in one click.

Try the Flexbox & Grid Playground →