Skip to content

Sticky Header on Scroll

A webpage header can be fixed at the top of the page using CSS and jQuery. The best way to do this is to set a new CSS class for the fixed position that will get assigned to the relevant div when scrolling goes past a certain point.

Additionally, you may have to assign css z-index to either the header or content div to prevent overlaying content over the header as it is scrolled.

HTML

<div class="header"></div>
<div id="content">
...
</div>

CSS

.fixed {
    position: fixed;
    top:0; left:0;
    width: 100%;
 }
#content {
    z-index: -99;
}

jQuery

$(window).scroll(function(){
  var header = $('.header'),
      scroll = $(window).scrollTop();

  if (scroll >= 100) header.addClass('fixed');
  else sticky.removeClass('fixed');
});

Tags: