Center elements with Tailwind CSS


Using Tailwind CSS to center a div element vertical & horizontal with flexbox or CSS grid allignment.

25 Jun, 2021 Β· 2 min read

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

We'll be looking at two methods of centering a div with Tailwind. 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 details. For our demo, we'll use the same CSS structure so you can see the difference in both examples better.

1. Tailwind center div with grid center

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 this code is all we need? Let's explore what's going on.

  • grid: Gives the element a display: grid css 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 horizontally and vertically on the page.

See the Pen Grid center content using Tailwind CSS by Chris Bongers (@rebelchris) on CodePen.

Looking for a CSS Grid centered version?

2. Tailwind center div with flex center

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

Let's see how that would look like:

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

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:

See the Pen Flex center div using Tailwind CSS by Chris Bongers (@rebelchris) on CodePen.

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next πŸ“–

Creating an animated wave line with Tailwind CSS

10 Mar, 2022 Β· 4 min read

Creating an animated wave line with Tailwind CSS

Tailwind CSS Numeric font variants

9 Mar, 2022 Β· 3 min read

Tailwind CSS Numeric font variants

Join 2103 devs and subscribe to my newsletter