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

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:

View Output Full Screen Preview

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.