SyntaxStudy
Sign Up
css

How to Create a Sticky Navbar

Make a navigation bar that sticks to the top of the page when scrolling.

A sticky navbar stays visible at the top of the viewport as the user scrolls down. Use position: sticky combined with top: 0.

Steps

  1. Set position: sticky on the navbar element.
  2. Set top: 0 to anchor it to the top of the viewport.
  3. Add a z-index so it appears above other content.
  4. Give it a background color so content doesn't show through.

Tips

  • The parent element must not have overflow: hidden, or sticky won't work.
  • Use box-shadow to add depth when scrolling.
Example
nav {
  position: sticky;
  top: 0;
  z-index: 100;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 1rem 2rem;
}

/* Optional: shrink on scroll with JS */
nav.scrolled {
  padding: 0.5rem 2rem;
  transition: padding 0.3s;
}