Sticky navbar

Navigation is a key element of any website. However, this is a very complex element and creating a good navigation is a real art.

In this lesson, we'll learn how to create a navbar that all the time remains visible at the top of the screen when scrolling down the page, so that the user has easy access to it at all times.

This is not always the optimal solution, but in our case it will be desirable.

Step 1 - add basic navbar

Go to the navbar documentation page and copy the code of the Basic example. Then paste it just below opening <header> tag:

(We have learned basics about navbars in the previous tutorial, so I won't dwell on it here)

Step 2 - change the content of the navbar

Instead of the default elements in the basic example navbar, let's add some of our own. On the left there will be regular links, and on the right social media icons.

For icons we will use FontAwesome in the SVG version (we have learned about it in the previous tutorial).

Step 3 - stick the navbar to the top edge

Creating sticky navbar in Tailwind is easy. Simply add .fixed and .top-0 classes to the navbar:

However, before it works, we need to remove the .relative class from the navbar, because now it conflicts with the .fixed class.

Since our intro takes up 100% of the screen height and we have nothing outside of it, we can't see if anything has changed for now because we have nothing to scroll through. So for testing purposes, let's temporarily add a height to the <main> section, which is below the <header> section:

And now when you start scrolling you will see that our sticky navbar works as it should...partially. For some reason it seems like only the left side is stuck to the top of the screen and the right side is gone 🤨

Why? Because our navbar has a lower z-index CSS property value than our carousel.

An element with a higher z-index will cover an element with a lower z-index if they overlap.

However, we can easily fix this by adding the .z-10 class to the navbar, which will set z-index = 10, making it higher than in the carousel.

And now it works perfectly.

John Doe

About author

Michal Szymanski

Co Founder at TW Elements and MDBootstrap / Listed in Forbes „30 under 30" / Open-source enthusiast / Dancer, nerd & book lover.

Author of hundreds of articles on programming, business, marketing and productivity. In the past, an educator working with troubled youth in orphanages and correctional facilities.