“Hey, can you make that nav stick to the top?”
“Can we have the left sidebar follow the screen as they scroll?”
“What do you think about having the sub-header stick as they scroll?”
Questions like these used to strike fear into my heart. No. Really. I used to genuinely be afraid of this. Why? Because it was a pretty decent amount of work to make this effect possible.
I’m not talking about a simple fixed displayed header, that’s easy. Although…that does tend to throw in some problems when you have auto scrolls…anyway. What I’m referring to are elements that are static, and then at some point as the user scrolls, switch over to a fixed positioning.
This used to involve a lot of work. Detecting where the element was in the viewport, listening for the scroll, finding out when the element should stop, BLEH! Luckily, CSS is pretty baller and there is a new way to do this easily.
/* top, bottom, left, or right declaration */
Personally, I like the name. It suits what it does.
If you add position sticky to an element, that element will toggle between position relative and fixed, based on the user’s current scroll position. The only requirement for this to work is to have at least one of the following properties along with it: top, bottom, left, or right.
I would have to argue the most common implementation of this wicked feature would be to have a header, or nav, scroll with the user as they go through some content.
Let’s say we have three news articles, each with their own article title. We want the article title to scroll along with the user, so it stays in their sight, for as long as they are within that article. If we want it flush up against the top of the page, we can can do something like the following.
What if…you want the same effect, but you have your main navigation fixed to the top? Well, a slight change to the top property is all you need.
So you have a two column layout, and you want the left sidebar to follow the user? We can do that easily as well.
Here is the gotcha. Of course, right? Every cool thing has to have a gotcha.
Browser support is not great, but it is getting better. If we look at support combined with webkit, then we are looking at about 86.91% support. Not bad, but could be better.
That’s why, when it comes to implementing this feature, it should be a progressive enhancement. That way, no worries if it’s not supported. Will your user die if the sidebar doesn’t scroll along with the viewport? Probably not. If they do, then maybe they should’ve updated their browser.
Position sticky is a great feature! Though I do wish support was better, it is in the category now where you can consider it a progressive feature and can rest assured a good portion of your audience is going to be able to utilize it.
Thanks for sticking through the article!
…okay that was bad.