Vertically Center Align a div in Tailwind CSS

Tailwind CSS is a utility-first CSS framework that provides us with a set of pre-defined CSS classes that we can use to make web development faster.

In this article, we will see different ways to center a div vertically and horizontally using the Tailwind CSS framework.

Using Flexbox to Vertically Align a div

Flexbox is one of the popular ways to vertically center align a div using CSS. In tailwind too we can use Flexbox to center a div vertically and horizontally in the center of the screen.

In tailwind, we have to set the display property of the parent element to flex and use the align-items and justify-content properties to center the child element vertically and horizontally in the center of the screen.

Here is an example of aligning a div to the center of the screen using Tailwind CSS:

<div class="flex justify-center items-center h-screen">
  <div class="bg-blue-300 w-1/2 h-1/2"></div>
</div>

In the above code, we have used the h-screen class to set the height of the parent element to the full height of the viewport.

Next, we have used the flex, justify-center, and items-center classes to set the child element vertically and horizontally to the center of the screen.

Using Absolute Positioning to Vertically Center Align a div

Another way to center a div vertically in Tailwind CSS is to use absolute positioning. It helps to position an element relative to its containing element.

Here is an example of using Tailwind classes to use absolute positioning in an element:

<div class="relative h-screen">
    <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-blue-300 w-1/2 h-1/2"></div>
</div>

In the above code, we have used the relative class on the parent element, and then using the absolute class we have set the child element relative to the parent element.

Next, using top-1/2 and left-1/2 classes we have centered the element horizontally and vertically inside the parent div.

At the end using the transform and -translate-x-1/2, -translate-y-1/2 classes we have fine-tuned the position of the child element.

Using Flexbox and margin-auto to Vertically Align elements in Tailwind CSS

We can also use flexbox along with margin-auto to vertically and horizontally align an element in tailwind CSS.

Here is an example of how we can use the flex position and set the margin to auto to get the desired result:

<div class="flex h-screen">
  <div class="m-auto w-1/2 h-1/2 bg-blue-300">
  </div>
</div>

Here in this code, we have set the display property of the parent element to flex and then used the m-auto class to center the child element across the full-screen.

Conclusion

In this article, we have learned how to center a div horizontally and vertically using three different ways in Tailwind CSS.

The most popular one is by using flexbox but you can use absolute positioning depending on your needs.

Scroll to Top