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.
We can create a sticky header using JavaScript and without using JavaScript.
Sticky Header Using JavaScript
To create a sticky header we need to know pageYOffset and offsetTop.
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";
}
else
{
header.style.position = "static";
}
}, false);
Sticky Header Using CSS3
CSS3 supports sticky value for position property. Its the easiest way to create a sticky header.
{
position: sticky;
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
/* top distance from the window. Its has to be defined otherwise sticky won't work. */
top: 0px;
}
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
console.log("not supported");
}
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.
Leave a Reply