Sticky Header

What you will be creating

sticky-header

Following the trends on most site you going to see is the web pattern for sticky headers. In this article we will create a header that sticks to the top of the browser viewport with the least code possible and easiest to understand what’s going on.

We going to work with HTML, CSS and Jquery.

First let’s start with the HTML

HTML

Let’s say we want to company name in the left top corner and big splash screen. I’m using the placehold.it free image serving service to make a big enough image so we will be able to have a scroll bar.


<header>
<div class="logo">Company Name</div>
</header>
<img src="http://placehold.it/1600/1500/" alt="" /> 

CSS

Before we start styling our markup to first think what we to style and make it work.

  • The Default State
  • The Sticky State
  • CSS Transition State
header {
  position: fixed;
  width: 100%;
  height: 60px;
  padding: 40px;
  background: transparent;
  line-height: 1.5;
  color: white;
  transition: all 0.6s ease;
}

The Sticky state is .is-sticky class which we use the BEM naming convention. This class is the class you want to attach when the users scroll the viewport.


.is-sticky {
  font-size: 18px;
  height: 30px;
  padding: 20px 40px;
  background: slateblue;
}

jQuery

This is the part when most of the magic happens. We are using jQuery to detect the position of the viewport.

What we want to do when the user scrolls the header’s height in our example being 60px to attach the class name .is-sticky. And also when we reach the top to remove the is-sticky class name. This is how we achieve that by using Jquery.


$(window).scroll(function() {
if ($(this).scrollTop() > 60 ){ 
    $('header').addClass("is-sticky");
  }
  else{
    $('header').removeClass("is-sticky");
  }
});

Result

Here is the result that you can find on CodePen. Feel free to play with it and add more styles.

See the Pen PwZeVd by Hristijan Todorov (@htodorov) on CodePen.