Combine a nav with sticky position in a layout with 100vh (child of) body element?

Issue

In my page i prefer not to style the directly, but use a wrapper instead. Wrapper has min-height: 100vh. See the layout here: https://play.tailwindcss.com/ql9hVzG5mc.

Question: how to place a sticky <nav> with that layout?

Solution 1: place the <nav> as direct child of the <body>. Works, but a vertical scrollbar appear because the 100vh doesn’t take the <nav> height into account. Please note that i don’t know the height of the <nav>, so the wrapper can’t be min-height: calc(100vh - 32px), to say. Demo: https://play.tailwindcss.com/VGiGCnRrn0

Solution 2: place the <nav> as direct child of the <header>. It doesn’t work because, AFAIK (I may be wrong), the element should be a direct child of the body.

Solution 3: any ideas?

<body>
  <nav class="bg-orange-500 sticky top-0 p-4">
    nav
  </nav>
  <div class="flex flex-col min-h-screen bg-red-500">
    <header class="flex-shrink-0 bg-slate-500 p-4">
      header
    </header>
    <main class="flex-auto flex-shrink-0 bg-lime-500 p-4">
      main
    </main>
    <footer class="flex-shrink-0 bg-violet-500 p-4">
      footer
    </footer>
  </div>
</body>

layout

Solution

Use the min-h-screen with the body element instead and the rely on flexbox to extend the content

<script src="https://cdn.tailwindcss.com"></script>
<body class="min-h-screen flex flex-col">
  <nav class="bg-orange-500 sticky top-0 p-4">
    nav
  </nav>
  <div class="flex flex-col grow bg-red-500">
    <header class="flex-shrink-0 bg-slate-500 p-4">
      header
    </header>
    <main class="flex-auto shrink-0 bg-lime-500 p-4">
      main
    </main>
    <footer class="flex-shrink-0 bg-violet-500 p-4">
      footer
    </footer>
  </div>
</body>

Answered By – Temani Afif

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.