Coops answer is a good, simple solution, however, once you apply the fixed class the page becomes that much shorter and content will "jump" up, and if page is of a length where the scroll distance is less than the height of the header element, it will appear to jump and not let you see the bottom of the page.
The answer I found was to add a spacer div above the element that will become fixed (nav element in my case), and set it to the same height as the nav element, and set it to display none.
When adding the .fixed class to the nav, show the .nav-spacer div, and when removing it, hide it. Since the height of the page changes instantly I have set the duration to 0.
HTML
<header>the element above the element that will become fixed</header>
<div class="nav-spacer"></div>
<nav></nav>
CSS
nav {
position: relative;
height: 100px;
}
.nav-spacer{
position: relative;
height: 100px;
display: none;
}
.fixed {
position: fixed;
top:0;
left:0;
width: 100%;
/* I like to add a shadow on to the fixed element */
-webkit-box-shadow: 0px 5px 10px 1px rgba(0,0,0,0.25);
-moz-box-shadow: 0px 5px 10px 1px rgba(0,0,0,0.25);
box-shadow: 0px 5px 10px 1px rgba(0,0,0,0.25);
}
JavaScript
var stickyOffset = $('nav').offset().top;
$(window).scroll(function(){
if ($(window).scrollTop() >= stickyOffset){
$('nav').addClass('fixed');
//this makes the page length equal to what it was before fixing nav
$('.nav-spacer').show(0);
}
else {
$('nav').removeClass('fixed');
$('.nav-spacer').hide(0);
}
});