Published on

Vertical Align with Tailwind CSS Across Full-Screen Div

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Vertically Align a Div with Tailwind CSS

When working with Tailwind CSS, you might want to vertically center an element inside a full-screen div. You can achieve this easily using either Flexbox or CSS Grid utilities provided by Tailwind.

Solution 1: Using Flexbox

Tailwind CSS makes centering elements simple with flex, justify-center, and items-center.

<div class="flex h-screen items-center justify-center bg-gray-200">
  <div class="rounded bg-white p-8 text-center shadow-lg">
    <h3 class="text-lg font-semibold">Centered Heading</h3>
    <button class="mt-2 rounded bg-blue-500 px-4 py-2 font-bold text-white">Call to Action</button>
  </div>
</div>

Explanation:

  • flex → Enables flexbox.
  • h-screen → Makes the container take up the full viewport height.
  • items-center → Centers elements vertically.
  • justify-center → Centers elements horizontally.

Solution 2: Using CSS Grid

Alternatively, you can use CSS Grid for a cleaner approach.

<div class="grid h-screen place-items-center bg-gray-200">
  <div class="rounded bg-white p-8 text-center shadow-lg">
    <h3 class="text-lg font-semibold">Centered Heading</h3>
    <button class="mt-2 rounded bg-blue-500 px-4 py-2 font-bold text-white">Call to Action</button>
  </div>
</div>

Explanation:

  • grid → Enables grid layout.
  • place-items-center → Centers the child element both horizontally and vertically.
  • h-screen → Ensures full viewport height.

Frequently Asked Questions (FAQs)

1. What is the best way to center elements with Tailwind CSS?

Both Flexbox (flex + items-center + justify-center) and CSS Grid (grid + place-items-center) work well. Flexbox is great for single-axis alignment, while CSS Grid is best for two-dimensional layouts.

2. How do I align text inside a div using Tailwind CSS?

Use text-center to horizontally align text and flex items-center to vertically align text inside a flex container.

3. What is h-screen in Tailwind CSS?

h-screen is a utility class that sets the height of an element to 100% of the viewport height (100vh).

4. How do I align multiple elements inside a flex container?

Use flex flex-col items-center to stack elements vertically while keeping them centered.

<div class="flex h-screen flex-col items-center justify-center bg-gray-200">
  <h3 class="text-lg font-semibold">Title</h3>
  <p class="text-gray-600">Subtext</p>
  <button class="mt-2 rounded bg-blue-500 px-4 py-2 font-bold text-white">Click Me</button>
</div>