Search code examples
jquerycssheaderfixed

How to fix a header on scroll


I am creating a header that once scrolled to a certain amount of pixels it fixes and stays in place.

Can I do this using just css and html or do i need jquery too?

I have created a demo so you can understand. Any help would be great!

http://jsfiddle.net/gxRC9/4/

body{
     margin:0px;
     padding:0px;
}
 .clear{
     clear:both;
}
 .container{
     height:2000px;
}
 .cover-photo-container{
     width:700px;
     height: 348px;
     margin-bottom: 20px;
     background-color:red;
}
 .small-box{
     width:163px;
     height:100px;
     border:1px solid blue;
     float:left;
}
 .sticky-header{
     width:700px;
     height:50px;
     background:orange;
     postion:fixed;
}



Solution

  • You need some JS to do scroll events. 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.

    HTML

    <div class="sticky"></div>
    

    CSS

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

    jQuery

    $(window).scroll(function(){
      var sticky = $('.sticky'),
          scroll = $(window).scrollTop();
    
      if (scroll >= 100) sticky.addClass('fixed');
      else sticky.removeClass('fixed');
    });
    

    Example fiddle: http://jsfiddle.net/gxRC9/501/


    EDIT: Extended example

    If the trigger point is unknown but should be whenever the sticky element reaches the top of the screen, offset().top can be used.

    var stickyOffset = $('.sticky').offset().top;
    
    $(window).scroll(function(){
      var sticky = $('.sticky'),
          scroll = $(window).scrollTop();
    
      if (scroll >= stickyOffset) sticky.addClass('fixed');
      else sticky.removeClass('fixed');
    });
    

    Extended example fiddle: http://jsfiddle.net/gxRC9/502/