JT Book a call

Blog

Tailwind CSS Vertical Center - Full Screen Flexbox

Published

2 min read

Tailwind CSS Vertical Center - Full Screen Flexbox
In this post

How can vertically align an element with Tailwind CSS by Flex?

Justify-Center and Items-Center #

  • flex : To use a flex-div as a container.
  • h-screen : To size the container height to the viewport height.
  • justify-center : To justify center (horizontal center).
  • items-center : To align the items to the center (vertical center).
<div class="flex h-screen items-center justify-center">
  <h1>Title</h1>
</div>

Image description

This is already pretty well documented in the Tailwind CSS docs.

The two utilities split the job by axis. justify-center is justify-content: center, which works along the flex direction, and items-center is align-items: center, which works across it. With the default flex-row, that means horizontal and vertical. If you add flex-col, the axes swap, and justify-center becomes the vertical one.

Another way to use Flex for to align items #

In this case need to set margin: auto to wrapper of children element.

<div class="flex h-screen">
  <div class="m-auto">
    <h1>Title</h1>
  </div>
</div>

This works because an auto margin in a flex container takes all the free space on its side. With m-auto, the child gets equal free space on all four sides, so it lands in the middle.

h-screen on phones #

h-screen is height: 100vh. On mobile browsers the address bar slides in and out, and 100vh can be taller than what is visible while the bar is showing, so your “centered” title sits a bit too low. Tailwind CSS v3.4 added h-dvh (height: 100dvh), which follows the viewport as the browser UI expands or contracts:

<div class="flex min-h-dvh items-center justify-center">
  <h1>Title</h1>
</div>

We used min-h-dvh here on purpose. With a fixed h-dvh and content taller than the screen, items-center pushes the overflow out of both ends of the box. In a 600px-tall window, a 900px child started 150px above the top of its container. With the container at the top of the page, that part can’t be scrolled into view. With min-h-dvh, the container grows to fit, and short content stays centered.

To keep the rest of the stylesheet maintainable, see How to have a clean CSS structure with RSCSS/ITCSS.

If you inherited a codebase where the team rolls custom layout hacks instead of using Tailwind’s built-in utilities, that’s a sign worth digging into. Our code quality evaluation guide helps non-technical founders spot these patterns before they compound.

For more Tailwind CSS techniques, see our guides on creating triangles in Tailwind and pure CSS triangles.

Read next

Tell us what you need built

JetThoughts has been building software since 2008. Book a call, or write to sales@jetthoughts.com. You'll leave the call with a written one-page scope within 2 working days.

#01 Paul Keen
Paul KeenFounder & Open Source Contributor

A 30-minute call; pick a time.