Make it stick! Sticky headers in CSS 🦎🔝
Sticky headers are simply to implement in CSS. There is a specific property value for it - position: sticky!
The idea is straightforward: If an element has position: sticky, treat it as a normal position: relative block, as long as it’s on screen. If the user scrolls far enough that the element (let’s say it’s a h1) will move off the screen, but it’s parent is still visible onscreen, treat it as though it were position: fixed.
So, how do you make sticky headers with just css?
It’s super-easy! All you do is:
.stayOnTop {
position: sticky;
top: 0;
} The position is set through the properties: top, left, right, bottom. So, to have the element stay on top, use top: 0;.
Tables
One of the best use cases for this is for tables. Any table where you want to see the column headers on top as you scroll down.
You can use it to make sticky headers on the side and top for easy cross-referencing for big data sets, maybe you’re showing scientific findings like below! So, it kind of mimics frozen rows in Excel!
Other use cases
Here are some other use cases I have seen on my web travels.
Hero section
It is used often to make a sticky navigation bar when there is a hero section above it. The navigation bar becomes fixed when the user scrolls past the hero section.
Reading progress bar
I think the example below is cool, but it requires some JS. A reading progress bar for a blog post. Scroll to see it in action. You can get creative with sticky too!
I wrote an article about how I made this if you are interested!