Skip to main content

Command Palette

Search for a command to run...

How to center a Div element with Tailwind CSS

Updated
2 min read
How to center a Div element with Tailwind CSS
A

Frontend Developer | React & Next.js | Web3 Explorer I build scalable web applications and love breaking down complex tech into simple ideas. Learning, building, and sharing—one project at a time ⚡

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 Tailywind 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.

In the Codepen demo below, we’ll use the same CSS structure, so you can see the difference between the Tailwind Grid center and Tailwind Flexbox center.

1. Tailwind center div with CSS Grid

We’ll start by using grid center to make a div element horizontally and vertically centered on a page.

<div class="grid h-screen place-items-center">Centered using Tailwind Grid</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

Demo Tailwind grid centerpermalink

This CSS code will perfectly center the div element horizontally and vertically on the page:

Looking for a CSS Grid centered version?

2. 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.

  • flex: Adds the display: flex CSS property

  • justify-center: This centers the div horizontally

  • items-center: This centers the content vertically

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

The final CSS code will look like the following:

Example Tailwind flex center

Looking for the CSS Flex center article?