How to center a div in tailwind css

How to center a div in tailwind css

Wednesday, November 4, 2026, 9 AM

Centering a div in Tailwind CSS usually comes down to two options: Flexbox or CSS Grid. The most common way to do it is by applying flex, items-center, and justify-center to the parent container.

I find myself using Flexbox for most layouts because it feels more intuitive for simple alignment. If you want to center a login card in the middle of a viewport, you need to make sure the parent container has a defined height. Without a height, the div will only center horizontally because the container is only as tall as its content.

Using Flexbox for centering

To center an element both ways, apply flex to the parent. The items-center utility handles the vertical alignment, while justify-center handles the horizontal alignment. I used this recently for a dashboard loading state.

<div class="flex h-screen w-full items-center justify-center bg-gray-100">
  <div class="w-64 rounded bg-white p-6 shadow-lg">
    <p class="text-center">Loading your profile...</p>
  </div>
</div>

In this example, h-screen is vital. It tells the browser that the parent should take up 100% of the viewport height. If you omit that, the inner div stays at the top of the page because the parent has no height to center within.

The CSS Grid shortcut

If you want the shortest possible code, Grid is actually faster. You can use the place-items-center utility. This combines justify-items and align-items into one single property. It is great for landing page hero sections or centering icons inside buttons.

<div class="grid h-64 w-full place-items-center border-2 border-dashed">
  <button class="bg-blue-600 px-4 py-2 text-white">
    Upload File
  </button>
</div>

A mistake I see often is trying to use mx-auto to center a div vertically. The margin-auto utility works perfectly for horizontal centering on block elements with a fixed width, but it does nothing for vertical centering. For vertical alignment, you must use Flex or Grid on the parent container. People spend a lot of time fighting with margins when a simple grid on the parent would have fixed it in seconds.

Posted in: Web Development

Comments

No comments yet