Published on

Fixing Tailwind h-screen Container Offset Issue

Authors
  • Name
    Ripal & Zalak
    Twitter

Fixing Tailwind h-screen Container Offset Issue

When using h-screen in Tailwind CSS with a fixed or positioned header, you may notice that the content is pushed beyond the bottom of the viewport. This happens because h-screen takes up 100vh (100% of the viewport height), but the header is also occupying space, causing the layout to extend beyond the screen.

The Issue

If you have a layout with a sidebar, top navigation, and main content like this:

const style = {
  container: `h-screen overflow-hidden relative`,
  mainContainer: `bg-gray-800 flex flex-col pl-0 w-full lg:w-[calc(100%-13rem)]`,
  main: `bg-gray-100 h-screen overflow-auto lg:rounded-tl-3xl`,
}

return (
  <LayoutProvider>
    <div className={style.container}>
      <div className="flex items-start">
        <SideNavigation />
        <div className={style.mainContainer}>
          <TopNavigation />
          <main className={style.main}>{children}</main>
        </div>
      </div>
    </div>
  </LayoutProvider>
)

The issue occurs because the h-screen in main does not account for the height of TopNavigation, causing it to overflow.

The Fix: Adjust h-screen with calc()

Since the header is 74px tall, adjust the height of main by subtracting the header height from 100vh:

const style = {
  main: `bg-gray-100 h-[calc(100vh-74px)] overflow-auto lg:rounded-tl-3xl`,
}

Now, the main section will only take up the remaining space below the header, preventing overflow.

Alternative Fix: Using min-h Instead of h-screen

Another approach is to use min-h-[calc(100vh-74px)], ensuring that the height does not shrink below the remaining viewport space:

const style = {
  main: `bg-gray-100 min-h-[calc(100vh-74px)] overflow-auto lg:rounded-tl-3xl`,
}

This ensures the content always has the minimum height required but allows for scrolling when content exceeds the available space.

FAQs

1. Why is h-screen not working correctly?

h-screen sets an element’s height to 100vh, which does not account for fixed headers or navigation bars, causing overflow issues.

2. Can I dynamically calculate header height?

Tailwind’s calc() function does not support variables, but you can use media queries:

<div className="sm:h-[calc(100vh-74px)] md:h-[calc(100vh-80px)] lg:h-[calc(100vh-90px)]">

3. What if I have multiple fixed elements?

If you have both a fixed header and a footer, subtract both heights:

const style = {
  main: `bg-gray-100 h-[calc(100vh-74px-50px)] overflow-auto`,
}

Where 74px is the header height and 50px is the footer height.