Navbar fixed top after scrolling

Four methods to keep a navbar at the top of the screen.

25 November, 2018
Time to read: 2 mins
CSS
Last update: 12 September, 2019
Table of contents
  • Position fixed
  • Scroll event
  • Intersection observer
    • Caveats
  • Position sticky

In this post, youll see 4 methods you can use to keep a navigation bar at the top of the screen while the user scrolls down the page. Its useful for single-page applications where the pages tend to get long, and you want to give the user the option to jump from section to section without having to go all the way up.

See a GitHub repository with the examples.

Position fixed

In the past, the easier way to achieve this was to give the element a position: fixed and place it at the top-left of the screen. For example:

.navbar { position: fixed; width: 100%; top: 0; left: 0; }Copy

This code removes the navbar from the normal content flow and places it at the top of the screen. As a result, the rest of the content tries to fill up the space the navbar leaves and goes under it. If you want to avoid hiding elements behind the navbar, you can either add a top margin to the rest of the contentequal to the navbar heightor make the navbar transparent.

Scroll event

If you want some kind of transition/animation, you can give the navbar a default relative position and then create a listener for the scroll event. Inside the scroll listener, you implement the following: if the distance from the top of the screen is greater than the navbar height [we moved passed the navbar], you add a scrolling class to the navbar. That class changes [with CSS code] the position to fixed and the other properties you want to transition. Consider the following CSS code:

/* default state */ .navbar { position: relative; /* default colors + transition */ background-color: white; color: black; transition: all 0.3s ease-out; } /* scrolling state */ .navbar.fixed-top { position: fixed; top: 0; width: 100%; /* scrolling colors */ background-color: black; color: white; } .navbar.fixed-top a { color: white; }Copy

and the JavaScript code:

document.addEventListener["scroll", function [] { const navbar = document.querySelector[".navbar"]; const navbarHeight = 100; const distanceFromTop = Math.abs[ document.body.getBoundingClientRect[].top ]; if [distanceFromTop >= navbarHeight] navbar.classList.add["fixed-top"]; else navbar.classList.remove["fixed-top"]; }];Copy

Intersection observer

A more modern and performant alternative is to use an intersection observer instead of a scroll listener. First, you add a zero-height div below the navbar, and you give it a .spot class.

Position fixed Scroll event Intersection observer Position sticky Copy

Then, you initialize an IntersectionObserver and start observing that spot element with observer.observe[spot]:

// element references const navbar = document.querySelector[".navbar"]; const spot = document.querySelector[".spot"]; // initialize and start the observer. const observer = new IntersectionObserver[handleScroll, options]; observer.observe[spot];Copy

When you initialize the observer, you pass some options and a handleScroll method:

// element references const navbar = document.querySelector[".navbar"]; const spot = document.querySelector[".spot"]; // handler const handleScroll = [entries] => { const spotIsVisible = entries[0].isIntersecting; if [spotIsVisible] navbar.classList.remove["fixed-top"]; else navbar.classList.add["fixed-top"]; }; const options = { root: null, rootMargin: "0px", threshhold: 0, }; // initialize and start the observer. const observer = new IntersectionObserver[handleScroll, options]; observer.observe[spot];Copy

The handler and the options give the following behavior: If the spot is completely hidden [not intersecting], we add a scrolling class to the navbar; if even 1px is visible [intersecting], we remove that class. The handleScroll method is called in both cases.

Caveats

  • Both of the last two methods [intersection observer/scroll listener] can cause the page to momentary jump when the transition happens, due to the removal/addition of the navbar from the normal content flow.
  • If the .spot div has a height other than 0, or if you observe the navbar instead of the spot, you may get stuck in an infinite loop where you add/remove the fixed-top class from the navbar.

Position sticky

The last option you have is my favorite. Its easy as the first method but without the margin drawback [the rest of the content doesnt go behind the navbar]. Additionally, the transition is smooth and doesnt cause that jump I described earlier. You achieve that by giving the navbar a position: sticky; and by placing it at the top of the screen:

.navbar { position: sticky; top: 0; background-color: transparent; } #content { background-color: aquamarine; }Copy

I also made the navbar transparent and the content aquamarine to prove that the content doesnt go under the navbar. If you want to add a transition, you can register an intersection observer, but this time, you dont have to change the position when the navbar is fixed-top.

Position sticky is supported by all the major browsers.

Subscribe to the Newsletter

Get an email when I publish a new post. I wont send you spam, and you can unsubscribe at any time.

Email:Subscribe

Other things to read

Popular

  • Reveal animations on scroll with react-spring
  • Gatsby background image example
  • Extremely fast loading with Gatsby and self-hosted fonts

Previous/Next

  • Using redux
  • Deploy a local WordPress site with the UpDraftPlus [free] plugin
Load comments

Video liên quan

Chủ Đề