Cover photo credit: Mae Mu
position: sticky to the rescue!
position: sticky is the answer to solving this problem, but how does it work?
Basically, an element with
position: sticky is treated like
position: relative until the block that contains it crosses a specific threshold. This is usually done by setting either
left to a specific value at which point it “sticks” in that position.
Here’s a quick example:
If you scroll the container you’ll notice that the header sticks to the top!
position: sticky and
top: 0 create the behavior you’re seeing. That’s it!
Let’s look at another example, a contact list. We want the current first letter of the names we are looking at to be pinned to the top. This might seem more tricky, but it’s actually very similar. It turns out that you can have multiple elements set to be sticky and they will naturally supersede one another! The same two properties solve this problem as well!
This can come in handy for other use cases like section headers.
This works well for headers, but what about a footer? This one is just as simple as the first two, swap out setting
top: 0 for ‘bottom: 0` and you’re good to go!
Footers have never been easier to create!
These apply the exact same way as header and footer, just set
left: 0 or
right: 0. Then with a horizontally scrolling section you can have sections stick to the left or right!
This can come in handy for creating things like slide shows where content naturally flows horizontally.
The nice things about
position: sticky is that it’s a true progressive enhancement. In every use case we’ve discussed it doesn’t break functionality. It simply makes it a better user experience. This means our friends using IE11 will not be missing any critical functionality, they just won’t get the best user experience we have to offer.
Compatibility looks like this:
So the quick summary is, it’s AWESOME.