Sticky Things

This week I have been working on a new navigation/header component which is supposed to work as a sticky header—people nowadays seem to want that by default. I started to write some JavaScript to make it stick to the top of the page when the page scrolls. It needed some offset to the body to avoid a rather annoying page jump, once it hits the sticky threshold. After I got it working, I remembered position: sticky which has been introduced in the second draft of CSS Positioned Layout Module Level 3 in 2015. I went ahead, tried it out and I have to say I’m a big fan now, simply because of its simplicity.

To make it work, all you have to do is add position: sticky; to your desired sticky element and specify the position of where you want your element to stick.

.sticky-element {
    position: sticky;
    top: 0;
}

Browser support isn’t great yet, but in my case the advantages outweigh the tradeoffs.

  1. No JavaScript needed. Even though it would only require a few lines of JS, it’s great to have a CSS-only solution;
  2. Super-simple implementation;
  3. If the browser doesn’t support it, it’s not a big deal if the element does not stick, but scrolls out of the viewport.

Support for this will get better over time and I’m very much looking forward for wider browser support. CSS has come such a long way and it keeps getting better and better :)

Details on browser support can be found here:

  1. https://developer.mozilla.org/en-US/docs/Web/CSS/position
  2. https://caniuse.com/#search=sticky