center elements with Tailwind CSS

How to center elements with Tailwind CSS (vertically & horizontally)

Tailwind CSS is my favorite CSS framework of all time. I’ve been using Tailwind CSS a lot lately, and I wanted to quickly show you how I use it to center a div. In this article, I’ll show you how to rapidly center elements with Tailwind CSS.

We’ll examine two different ways to center a div in Tailwind. There is no apparent winner or loser when it comes to these two strategies. In general, flexbox CSS should be used for details and CSS grid for high-level layout.

We’ll use the same CSS structure for our demonstration so you can understand the differences between the two cases more clearly.

Tailwind CSS center div with grid classes

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

Optionally you can use the tailwind CSS class justify-center with grid items-center to perfectly align items in the center.

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

Tailwind CSS center div with flex classes

<div class="flex justify-center items-center h-screen">
  Centered div using Tailwind flex classes
</div>
  • 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 same classes can be used with either flex-row or flex-col, which position the flexbox’s primary axis horizontally or vertically.

Setting the height using min-h-screen is a simple approach to filling a full screen with content.

Read also: How to create a smooth scroll in CSS and JavaScript?

AdBlocker Message

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.