Center elements with Tailwind CSS

β€” 3 minute read

permalink

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 permalink

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

<div class="grid place-items-center h-screen">
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 permalink

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 justify-center items-center h-screen">
Centered using Tailwind Grid
</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:

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! permalink

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