In this post I will be providing best and easiest solution to implement a sticky header in your website. Its no brainer to create a sticky header. There has been many solutions to create a sticky header. In this post I will provide my favourite ways of doing it.
Now we can check if the header has been scroll up using this condition
headerElement.offsetTop <= window.pageYOffset
This is an example event handler to check if the header is scrolled up or not
if(header.offsetTop <= window.pageYOffset)
//make it sticky
header.style.position = "fixed";
header.style.position = "static";
Sticky Header Using CSS3
CSS3 supports sticky value for position property. Its the easiest way to create a sticky header.
/* top distance from the window. Its has to be defined otherwise sticky won't work. */
The problem with this property is that its not yet supported by many web browsers.
We can check if sticky css value is supported or not by this snippet
Sticky position is relative to its containing block i.e., if the containing block goes out of viewport then the element is no more sticky.
There is a Polyfill for position sticky position–sticky-. We can use this if browser doesn’t support sticky natively.