At some point in your career as a web developer you will be asked to “just make it stay at the top while they scroll.” This has been something javascript has solved for us in past, but no more! position: sticky to the rescue!

Just make it stay at the top

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 top or left to a specific value at which point it “sticks” in that position.

Here’s a quick example:

See the Pen Basic Position Sticky by Andy Desmarais (@terodox) on CodePen.

If you scroll the container you’ll notice that the header sticks to the top!

Just setting position: sticky and top: 0 create the behavior you’re seeing. That’s it!

Stacking sticky headers

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!

See the Pen Stacked Position Sticky by Andy Desmarais (@terodox) on CodePen.

This can come in handy for other use cases like section headers.

Sticking to the bottom

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!

See the Pen Sticky Footer by Andy Desmarais (@terodox) on CodePen.

Footers have never been easier to create!

What about left and right?

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.

Browser compatibility

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:

It’s awesome