Vertical align with Tailwind CSS across full screen div
Using Tailwind CSS, simply flex, h-screen, justify-center, and items-center classes can vertically center the content within a full-screen 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:
<!--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:
Overflows? No worries!
Pair centering with overflow-auto to keep everything visible and accessible if your content tends to overflow:
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!
Was this article helpful?