Back to all posts

How to Center a Div Element with Tailwind CSS

A step-by-step guide to centering a div element using Tailwind CSS. Learn how to use Flexbox and CSS Grid utilities to align elements both vertically and horizontally with clean, minimal code examples.

Nowadays, I choose Tailwind CSS as my goto CSS framework. And today, I’ll show you how to center div elements with Tailwind CSS quickly.

We’ll learn how to center a div in the middle of the screen using two methods:

1.center a div element with Tailwind using Flexbox CSS

2.use CSS Grid to center an element

There isn’t a clear wrong or right choice between these two methods. Generally, CSS grid should be used for the high-level layout and Flexbox CSS for lower-level HTML elements, such as details.

Tailwind center div with CSS Grid

<div class="grid h-screen place-items-center">Centered using Tailwind css</div>


Can you believe these Tailwind classes is all we need to center vertically and horizontally?

Let’s explore the classes.

grid: Gives the element a display: grid css property

place-items-center: Gives it the center value on the place-items property, centering

h-screen: Sets the 100vh (screen-height) as the height

Tailwind center div with CSS Flexbox

A second option to center in Tailwind is to use CSS Flexbox for the HTML element. The method is pretty similar, but we have to specify the horizontal and vertical alignment with Flexbox.

Let’s see how centering looks with Flexbox:

<div class="flex items-center justify-center h-screen">
Centered using Tailwind Flex
</div>

As you can see, the div alignment looks similar to the first example but with an extra variable.

1.flex: Adds the display: flex CSS property

2.justify-center: This centers the div horizontally

3.items-center: This centers the content vertically

4.h-screen: Sets the 100vh (screen-height) as the height

Thank you for reading the tutorial