Solving the sticky element problem can lead to sticky situations
When navigating sites, it is common to see HTML elements, like banners and navigations, sticking to the top and bottom of the browser. There are a couple of ways that can be done.
One, there is position: sticky, a native CSS feature. You might use it something like this:
MDN explains it well:
Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.
I’d say that neither of these techniques are quite ideal.
By doing the flip-flopping yourself, there may be jumpiness when these elements go from fixed position to not. This issues is worsened in mobile device browsers.
With native CSS alone, you don’t have the ability to know when the element is in one state or the other.
Get the best of both worlds with StickyBits
Stickybits a lightweight (~2KB) alternative to position: sticky polyfills. It is an easy to set up plugin that is cross-compatible with any other plugins, libraries, or frameworks.
Installation with npm:
npm i stickybits –save-dev
Or, installation with Yarn:
yarn add stickybits –dev
With the out-of-the-box solution above, you now have set any element with your selector to be sticky. This will work for browsers that support .classList whether position: sticky is supported or not.
Stickybits, with the additional useStickyClasses: true property set will add sticky and stuck classes when elements become sticky or stuck. This makes it easy to hook up CSS styles based on when the selected element become static, sticky or stuck. This useful utility was added after Dave Rupert mentioned it on the Shop Talk Show Podcast.
Stickybits also supplies offset properties and a clean-up method hook to help better manage its sticky state.
See the Pen Njwpep by Jeff Wainwright (@yowainwright) on CodePen.
See the Pen CSS `position: sticky` example by Jeff Wainwright (@yowainwright) on CodePen.
More demos provided on GitHub.
Stickybits was inspired by FixedSticky from Fillament Group, who has recently deprecated their plugin.
It is open-sourced by Dollar Shave Club and maintained by our team and I.