Create a fixed navbar with TailwindCSS
<body>
<header class="h-12 bg-sky-300 sticky top-0 z-50">Navbar</header>
<main class="h-[2000px]">Main content container</main>
</body>
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:
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:
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:
Note: Don't forget the top-0
, z-50
, h-12
utilities.
- Create blinking background with TailwindCSS
- Create a neon effect with TailwindCSS
- Rotate element with TailwindCSS
- Change SVG icon color with TailwindCSS
- Using :not in TailwindCSS
- Specify exact width value in TailwindCSS
- Set element width over 100% using Tailwind CSS
- Stretch children to fill horizontally
- Create a fixed navbar with TailwindCSS
- Use font from local files in TailwindCSS
- Make an element invisible in mobile size in Tailwind CSS
- Create a 20/80 grid with Tailwind CSS
- Select the nth child in TailwindCSS
- Add class to child when hovering on parent in TailwindCSS
- Fill the full height of the screen in TailwindCSS
- Create transition with TailwindCSS
- Create horizontal rule with text using TailwindCSS
- Set background image with TailwindCSS
- How to use CSS variables in TailwindCSS
- Center an absolute element in TailwindCSS
- Remove arrows from number input in TailwindCSS
- How to use !important in TailwindCSS
- Select first child in TailwindCSS
- Access child elements in TailwindCSS
- Create semi transparent background in TailwindCSS
- How to use calc() in TailwindCSS
- Add text shadow with Tailwind CSS