Header sticky on scroll

Header sticky on scroll up

Sticky headers are fixed the div or section to the top of the website, and are visible even when you scroll down.

Sticky navigation is a terms of used to describe a fixed navigation menu on a web page.  Web page header remains visible and in the same position as the user scrolls down and moves about a site.

You can actually build one using some CSS Styles

To make the header sticky, we need to add some CSS code to the header element:


#sticky.stick{

Position:fixed;Top:0;Z-index:10000;Border-radius:0 0 0.5em 0.5em;

}

The position: fixed CSS property  is used to fix the header to any part of the visible page.

position: fixed CSS property that is lockes the website menu  so that it does not disappear when the user scrolls down the page.

Then the top: 0 property sets the header to be zero pixels from the top of the page, i.e. at the very top.

setting the position property to fixed will make the header element behave very similarly to position: absolute, which takes the element out of the normal “flow” of the page.

This means that you will have to manually set a width for the element. and it will make to go all the way across the page. We also had to set width: 100% in order for the header to display the way we wanted.

Now if we reload the page and try scrolling down, we can see that the header remains on the page and at the very top, all the time.

<div id="sticky-anchor"></div>
<div id="sticky">This will stay at top of page</div>

CSS

#sticky {
padding: 0.5ex;
width: 600px;
background-color: #333;
color: #fff;
font-size: 2em;
border-radius: 0.5ex;
}
#sticky.stick {
position: fixed;
top: 0;
z-index: 10000;
border-radius: 0 0 0.5em 0.5em;
}

Javascript

function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});