Member-only story
Sticky HTML Elements Done the Right Way
Best practices to create elements that stick as you scroll
Nowadays there is a very common pattern when scrolling past an important element we want to remain there for the user at all times: making it stick. There is an out-of-the-box solution built right into CSS which is position: sticky
and position: -webkit-sticky
. For this property to work, it needs more info on how to behave and that’s where bottom
, top
, left
, and right
come into play. Without that extra information, position: sticky
won’t do anything as it lacks crucial information; it will be treated like position: relative
. If you have ever tried it and it didn’t work for you, that’s probably the reason.
Assuming the happy path, you can achieve the sticky effect in just a couple of CSS lines, like in the example below:
In return, you will be getting something like the following.

This is pretty sweet, and the article could probably finish here. But what happens to browsers that don’t support this? You can see that the feature has great support, but still some browsers are falling behind. For browser support, caniuse.com is always our best friend:

Fortunately we have a tool to check on the fly if a browser does support some CSS properties or not. The Css.supports
method returns a Boolean
value indicating whether the browser supports a given CSS feature. This is a very interesting API, and you can check it out in more detail.
For our use case, what we want to be checking is: