Have a div cling to top of screen if scrolled down past it
To make a div
stick to the top during scroll, utilize this position: sticky; top: 0;
style
Apply this style like so:
The sticky-top
div will remain in the viewport once you've scrolled past it, because position: sticky;
kicks in when the element's position hits top: 0
.
Stickiness with JavaScript or jQuery
To handle older browsers that don't support position: sticky;
, let's toggle a sticky class with JavaScript or jQuery based on the scroll position.
Determining barometer for stickiness
Cached selectors swagger
Cache the selectors to reduce DOM access. Adding this will make your performance go from "meh" to "whoa".
Prevent layout shift with CSS and HTML
Add an empty div to prevent a flickering layout when the div
becomes fixed.
Establish stickiness class and toggle on scroll
Define the sticky class in CSS and toggle it with JavaScript or jQuery:
Using jQuery, class toggling becomes a one-liner. jQuery surely has the ring for our class toggling needs.
Maneuvering anchor links
"If you gaze long into the scroll, the scroll also gazes into you." - Friedrich Scrollszsche
When you use sticky headers with anchor links, the page might scroll too far, hiding the beginning of the anchored section. Add some shift to the scroll position:
Was this article helpful?