Happy holiday folks! All the best from us at Digitpaint

Day 21

Adhesive action with position: sticky!

Say goodbye to all your JavaScript handling your sticky navbars! No more scroll event handlers, fixes for jumping content when you make things fixed. Sounds farfetched to you? Well, it isn't anymore! Meet position: sticky!

Demo time!

That's interesting, but where's the demo?

Look up.

Yes, right there at the top of your viewport

Whoa, where did those nave - elements com from?

We made 'em sticky!

PS. Scroll down past the bottom to see how what it does on reaching the end of a container.

Stick it!

Making elements sticky is done by setting the position CSS property to sticky. An element with position: sticky; starts it's life as would an element with position: relative. It will start to behave like a position: fixed element once it passes a certain part of the viewport (in this case, and by default, the very top). See for yourself by scrolling back up. The navigation buttons will always return to their starting positions.

Fixed v.s. sticky

There are two major differences between the fixedness of position: sticky elements and real position: fixed elements.

  1. Once an element becomes sticky, it will still reserve the space it has used. This means your content will not reflow and jump up and down. This also means no need to hack around using spacer or placeholder divs!
  2. Once the container of the element scrolls out of the viewport, it will also take the element with it. (Scroll down to see what we mean)

Browser compatibility

Sticky has been around quite a while. It was first added to webkit in 2012. One year later, after Google changed their engine from Webkit to Blink, they removed support for position: sticky; from their browser. It only worked on Webkit based browsers like Safari for a time. But FireFox added support for it about one year later. It did however then, and does not now support setting them on any table elements. In January of 2017, support for sticky positions was readded to Chrome. As of one of the next versions (probably 64) it's implementation will also support thead and tr elements. Microsoft added sticky goodness to Edge this October.

So all in all, browser support is pretty good right now. It just doesn't work on some elements yet, and needs a prefix to work on both iPhones and regular Safari.

  • chrome
  • edge
  • firefox
  • samsung
  • android chrome
  • safari -webkit- prefix
  • ios safari -webkit- prefix

Even more detailed information on caniuse.com

Learn more

Demo source code

About that demo … Show me the source please!

Back to home

Woah, what's all this free space?

But wait, look at that!

The navigation buttons stay inside their container!

That's neat 😎