Cheesetoast

Brain Food for Web Developers

Fixed Navbar

Fixed top menu that fades and shrinks when scrolled

This top menu bar will stick to the top of the page, but when the user scrolls down the menu will shrink slightly and become semi-transparent. I used javascript to add a CSS class with a transition effect applied.

See the Pen Shrink & Fading – Fixed Menu Bar by Graham Clark (@Cheesetoast) on CodePen.

HTML

We start with the html5 nav element with a fairly standard horizontal unordered list for the menu:

<nav>
  <ul>
    <li><a href="#one">One</a></li>
    <li><a href="#two">Two</a></li>
    <li><a href="#three">Three</a></li>
  </ul>
</nav>

CSS

nav {
  background: black;
  color: white;
  transition: opacity 1s ease;
  opacity: 1;

  height: 80px;
  line-height: 80px;
  width: 100%;

  position: fixed;
  top: 0;
  left: 0;
}
nav a {
  color: white;
  text-decoration: none;
}

nav:hover { opacity: 1 }

First I start by styling the visuals. The opacity is set to 1 with a CSS3 transition so that the changes are made smoothly.

The line-height is the same as the height of the nav bar, so that the text is vertically centered.

The position of the nav is fixed at the top left with a width of 100%.

Finally, I added a hover option that sets opacity to 1 again so the user can view the menu more clearly.

Next I’ll add the class that javascript calls when the user scrolls:

.scrolled {
  opacity: 0.7;
  height: 50px;
  line-height: 50px;
}

JAVASCRIPT (JQUERY)

$(window).scroll(function(){

  var scroll = $(window).scrollTop();

  if (scroll > 0 ) {
    $('nav').addClass('scrolled');
  }

  if (scroll <= 0 ) {
    $('nav').removeClass('scrolled');
 }

});

(Don’t forget to include jQuery if you’re using this code)

This code is pretty straight forward. As the user scrolls the function is called. The variable ‘scroll’ basically measures the amount of space from the top of the page to the top of the window, i.e. before you start scrolling the distance is 0.

Depending on the scroll amount, the javascript adds / removes the ‘scrolled’ class.

The CSS3 transitions will degrade gracefully and a lack of javascript support shouldn’t make anyone cry either. Hope this code has been of interest!

Author: Graham

My name is Graham and I'm a Scottish web developer living in California. I love working with clean code to make attractive and usable websites. I'm also interested in cooking, gardening, and taekwondo.

Comments are closed.