Creating a Sticky Navbar
To create a sticky navigation bar that stays at the top of the screen as you scroll, use the CSS position property with the sticky value and set top: 0.
A sticky navbar ensures that your site's navigation is always accessible to the user, even as they move down a long page. Unlike a fixed navbar, which is always in the same place, a sticky navbar only "sticks" once it reaches a certain point (usually the top of the browser window).
The Sticky Property
To make an element sticky, you only need a few lines of CSS applied to your nav or container element:
Why top: 0 and z-index are important
top: 0: This tells the element where to stop when it reaches the top of its parent container. Without this, the browser won't know the sticky position.z-index: Using a highz-indexensures that the navbar stays in front of other elements on the page as they scroll under it. Without this (or without a high enough value), the navbar may be hidden behind other elements.
Full Working Example
In the following example, notice how the navbar behaves like a normal element until you scroll past the header, at which point it sticks to the top:
Sticky vs. Fixed
A sticky element moves with the page until it hits its threshold (like the top of the viewport), while a fixed element is completely removed from the page flow and stays in a specific spot regardless of where it starts. Sticky is often preferred over fixed for navbars as it allows for a header above the menu that can scroll out of view first.