tpr Posted April 12, 2018 Share Posted April 12, 2018 I've been searching for a CSS-only solution for a while to reveal a scroll-to-top link only after scrolling down the page, but no luck. Today I figured out that it's possible with position: sticky. The beauty of this is that you don't need to check the scroll position in a scroll event (+ in document ready, window resize), which makes it really lightweight. Update: added "html { scroll-behavior: smooth; }" and now there's animated scroll (Firefox 58+, Chrome 63+). It seems that Js is not required anymore to this feature. CodePen demo 13 Link to comment Share on other sites More sharing options...
tpr Posted April 16, 2018 Author Share Posted April 16, 2018 I've adjusted the CSS so now the scrolltop link doesn't extend the page height if the page has small amount of content. That is, if there is not enough content to scroll the scrrolltop link doesn't show up and the page doesn't get any vertical scrollbar. In older browsers the scrolltop link shows up fixed even in this case but that's a minor thing imo. I've updated the example to have content toggle button so it's easy to see. 3 Link to comment Share on other sites More sharing options...
FrancisChung Posted April 16, 2018 Share Posted April 16, 2018 Great work TPR, I wrote some JS code to do this a while back, and it wasn't pretty ... at all. Thanks for this 1 Link to comment Share on other sites More sharing options...
tpr Posted April 19, 2018 Author Share Posted April 19, 2018 I noticed that in Firefox 59 using link href "#" and scroll-behavior: smooth didn't scroll up smoothly. I've added an id "top" to a top-level div and changed the href to "#top" so now it works as it should. Does anyone have some background info on this, or perhaps it's a bug? In earlier FF it worked fine if I remember right. Btw I also had to tweak the CSS because in FF the scrolltop link appeared below the fold if the page was smaller than the viewport. Link to comment Share on other sites More sharing options...
Recommended Posts