Center elements with Tailwind CSS

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

We'll be looking at two methods of centering with Tailwind.
There isn't a clear wrong or right between these two methods, but generally, grid should be used for the high-level layout and flex for details.
For our demo, we'll use the same structure so you can see the difference better.

1 Grid center using Tailwind CSS

We'll start by using grid to center an element perfectly within a page.

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

Can you believe this is all we need?
Let's explore what's going on.

  • grid: Gives the element a display: grid property
  • place-items-center: Gives it the center value on the place-items property
  • h-screen: Sets the 100vh (screen-height) as the height

This code will perfectly center the element on the page.

Looking for a CSS Grid centered version?

2 Flex center using Tailwind CSS

A second option is to use flex box to center the element.
The approach is pretty similar, but we have to specify the horizontal and vertical centering with flex box.

Let's see how that would look like:

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

As you can see, it looks similar to the grid option but with an extra variable.

  • flex: Adds the display: flex property
  • justify-center: Does the horizontal center
  • items-center: Does the vertical center
  • h-screen: Sets the 100vh (screen-height) as the height

This will result in the following:

Looking for the CSS Flex center article?

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

38