Explain Codes LogoExplain Codes Logo

Vertical align with Tailwind CSS across full screen div

html
responsive-design
tailwind-css
centering
Alex KataevbyAlex Kataev·Sep 23, 2024
TLDR

Using Tailwind CSS, simply flex, h-screen, justify-center, and items-center classes can vertically center the content within a full-screen div.

<div class="flex h-screen justify-center items-center"> <p>I'm center stage now!</p> </div>

The flex class is declaring a flex container, h-screen stretches it to cover the height of the viewport, justify-center handles horizontal centering, while items-center does the heavy lifting for vertical centering.

Expanding the center

While basic centering works, adding flex-col builds a vertical stack and flex-row sets up a horizontal layout within the full-screen div. Coupling m-auto to a child component provides a slick solution to perfect centering:

<div class="flex h-screen flex-col justify-center"> <div class="m-auto"> <p>Welcome to the center of the universe!</p> </div> </div>
<!--Fun Fact: The way `m-auto` works here to make elements beautifully centered reminds me of freshly baked chocolate chip cookies. Mmm...centered!🍪-->

Go responsive or go home!

Don’t forget responsive classes like md:flex and lg:justify-center. They allow you to keep your content perfectly aligned across devices (`cause nobody likes lopsided content, right? 💁‍♀️).

Pro-tip strategies

A fan of complex layouts? Use absolute inset-0 for precise positioning, where relative class comes handy when you need to postion containers within which absolute elements rest.

Nailing a perfect center

To prevent container collapse, make sure parent’s height is fully defined. Watch out for those sneaky collapsing margins, disrupting the peaceful centering! The text-center class is a true pal when it comes to text alignment within vertically centered elements.

Tailwind centering cookbook

When flexbox isn't enough

Combine relative positioning on a parent with absolute positioning on a child element:

<div class="relative h-screen"> <div class="absolute inset-0 m-auto"> <!-- Content below. Mailman: "Center delivery for Mr.Div" 📭 --> <p>Absolutely centered content</p> </div> </div>

Overflows? No worries!

Pair centering with overflow-auto to keep everything visible and accessible if your content tends to overflow:

<div class="flex h-screen overflow-auto p-4"> <div class="m-auto"> <!-- Overflow? More like "I've got this under control"😎 --> <p>Potentially large content here</p> </div> </div>

The magic of m-auto

Explained concisely - m-auto applies margin auto on all four sides, creating an equal space around it. This centers it blissfully within any flex container. Poof!