- Instant help with your CSS coding problems

Create a fixed navbar with TailwindCSS

Question:
How to create a fixed navbar with TailwindCSS?
Answer:
<body>
    <header class="h-12 bg-sky-300 sticky top-0 z-50">Navbar</header>
    <main class="h-[2000px]">Main content container</main>
</body>
Description:

It is a common task to make the navigation bar on a website permanently visible and to fix it at the top of the page for better navigation. That is why it is called a fixed navbar.
The task can be solved in TailwindCSS using fixed or the sticky utility class. 
However, when using a fixed class, you should also pay attention to the top padding of the main container. When you use the fixed utility class:

<body>
    <header class="h-12 bg-sky-300 fixed top-0 left-0 right-0 z-50 p-2">Navbar</header>
    <main class="h-[2000px]">Main content container</main>
</body>

the navigation bar hides the top of the content:

Fixed navbar hides content

To avoid this, you need to add a top padding to the main content container, equal to the height of the navigation bar. So if you change the height of the navigation bar, you also need to change the top margin.

<body>
    <header class="h-12 bg-sky-300 fixed top-0 left-0 right-0 z-50 p-2">Navbar</header>
    <main class="h-[2000px] pt-12">Main content container</main>
</body>

This results in:

Fixed navbar with top padding


For the above reasons, a better solution is to use a sticky utility. In this case, the navigation bar does not hide the main content. SO our code can be simpler:

<body>
    <header class="h-12 bg-sky-300 sticky top-0 z-50 p-2">Navbar</header>
    <main class="h-[2000px]">Main content container</main>
</body>

And the result is the same:

Sticky navbar with Tailwind

Note: Don't forget the top-0, z-50, h-12 utilities.

Share "How to create a fixed navbar with TailwindCSS?"
Interesting things
OpanAi's ChatGPT