Skip to main content

Command Palette

Search for a command to run...

Centering a div with tailwind - grid vs flex box

with key concepts, usecases, and examples

Updated
2 min read
Centering a div with tailwind - grid vs flex box
R

I am a fullstack developer. I share things that can make you a better developer. No paywalls.

If you’ve been using tailwind for a while, centering a div is easy.

There are two easy ways to center a div: grid place-items-center and flex items-center justify-center.

But do you actually know when to use one over the other?

Takeaway: "centering ONE thing → use Grid; arranging MULTIPLE things → use Flexbox"

The Core Idea

Both grid and flex box are powerful but serve a different purpose. .

Grid thinks in cells.

grid thinks in cells - understanding how css grid works

A Grid is best for ‘single responsibility’. When you write grid place-items-center, you’re saying - this container exists ONLY to center its child. It’s a 1×1 grid. One cell. With one item. Centered.

Use Grid for:

  • Modal overlays

  • Hero sections (single centered element)

  • Loading spinners

  • 404 pages

  • ‘One thing in the middle’ scenario

Flex box thinks in LINES.

flexbox thinks in lines- understanding how css flex box works

A flex box holds MANY things. When you write flex items-center justify-center, you’re saying - this container holds many items in a line. I want them centered horizontally and vertically right now, but I might change my mind later.

Use flex box for:

  • Navigation bars (even if you only have a logo right now; you’ll add menu items later)

  • Button groups (cancel + submit)

  • Card layouts

  • Form fields with labels

  • Anything that has (or will have) multiple children

Usecase?

GridFlex box
- single responsibility- you have multiple children
- think one item in a CELL- think items in a LINE (horizontal or vertical)

One child → use grid.

  • fewer classes: grid place-items-center

  • semantic: this is a centered cell

  • intent: ONE thing. centered.

Many children → use flexbox.

  • for rows/columns: flex items-center justify-center

  • flexible: change spacing like gap-4, change alignment like justify-between, justify-start

Examples

Technically, you can do the same with either - but you should use grid when you’re dealing with a single child.

Correct usage- for a single child.

And here’s how you’d use flexbox properly.

Final Thoughts

I’m sure you’re talented - you can use absolutely anything you want to center your divs. I hope you’re familiar with best practices now.