In this section, we’ll explore how to center a div in Tailwind CSS. We can achieve horizontal and vertical centering using both grid and flex.
Tailwind CSS Div Center
Center a div using Tailwind Flexbox classes .flex
, .justify-center
, and .items-center
.
<div class="flex justify-center items-center h-screen">
<div class="bg-gray-200 w-64 h-64">Centered Div</div>
</div>
Flexbox with Utility Classes
<div class="flex justify-center items-center h-screen">
<div class="bg-gray-200 w-64 h-64 flex justify-center items-center">Centered Div</div>
</div>
Absolute Positioning
<div class="relative h-screen">
<div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-gray-200 w-64 h-64">Centered Div</div>
</div>
Centering a div using Tailwind grid.
<div class="grid h-screen place-items-center">
<div class="bg-indigo-600 p-4 text-white shadow">Center Div</div>
</div>