This specific post aims to provide a quick intro to
position: sticky, a powerful attribute that I didn’t know about until recently. It works a bit like
position: absolute except that it will ‘stick’ to the viewport instead of scrolling up like a normally positioned element. This is hard to explain with words, so please check out my demo below to see what I mean.
Pretty cool, right?
I think that browser support of sticky positioning might be described best as ‘decent’, but not ‘good’. As of today, it looks something like this:
So basically it doesn’t work on IE or Edge, but I’m cool with that for two reasons:
- It will fail somewhat gracefully in most cases
Now we’ve covered what
- You will also need to track the distance that the sticky header is from the top of the viewport. This could be done with a throttled onscroll event, but your framerate could get ugly. Setting up a recursive requestAnimationFrame will probably give you the best UX in the end.
- Now you need to do the math to actually figure out if the sticky header is at the top or not, and set its position to fixed when it is.
- In my experience, the animation in which the elements transitions from scrollable to sticky just looks better with CSS. I’m sure this depends on what library you are using, however.
- I’ve had bad luck with bugs. In one case a new release of chrome caused a really strange bug for some users in the library I was using, which I never could recreate or solve. Eventually I just dropped the library and used a different solution.
All in all, I’m pretty excited that I came across this little CSS attribute and see myself using it a lot in the future.