Centering a div made easy with Tailwind CSS
Two ways to center an HTML element with Tailwind CSS, plus one newer option worth knowing about.
Somehow centering a div is still the problem everyone runs into, especially beginners getting started with web development. I wrote this a few years ago while exploring Tailwind, and the good news is that almost nothing here has changed. The utilities below work exactly the same in Tailwind v4.
Introduction
We will look at two ways of centering a div with Tailwind CSS, and then one newer option. There is no right and wrong choice, so use whichever you feel most comfortable with. Lets dive in.
1. Centering a div using Flex
We will start with flex, centering a div vertically and horizontally on the page. If you have not set Tailwind up yet, check my previous article for a quick run through on how to add it to your HTML project.
<div class="flex justify-center items-center h-screen">
Centered using flex
</div>
Lets break down what we just did:
- flex: adds the CSS flex property (display:flex).
- justify-center: centers the div horizontally.
- items-center: centers the content vertically.
- h-screen: not strictly necessary, but it sets the height to 100vh so there is something to center inside.
That was easy right? Lets move on to the second way.
2. Centering a div using Grid
A second option is Grid. Very similar to flex, with fewer classes.
<div class="grid place-items-center h-screen">
Centered using Grid
</div>
Lets break down what we just did:
- grid: gives the element a CSS grid property (display:grid).
- place-items-center: places grid items in the center of their grid areas (learn more).
- h-screen: sets the height to 100vh.
3. One newer option: h-dvh
The classes above have not changed, but the unit is worth revisiting. h-screen maps to 100vh, which on mobile browsers ignores the address bar sliding in and out. Your centered content ends up slightly off, or the page scrolls when it shouldn't.
Tailwind ships dynamic viewport units for exactly this:
<div class="grid place-items-center h-dvh">
Actually centered on mobile too
</div>
h-dvh maps to 100dvh, which tracks the visible viewport as browser chrome appears and disappears. Same centering, one less thing that looks broken on a phone. There is also h-svh (smallest viewport) and h-lvh (largest) if you want to pin to one or the other.
Thank you for reading. If you have any questions, feel free to contact me.