Jump to content

Reveal scrolltop link on scroll (CSS-only)


tpr
 Share

Recommended Posts

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.

scroll-to-top.thumb.png.d0877527f3943707daa69700f4357868.png

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

  • Like 13
Link to comment
Share on other sites

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.

  • Like 3
Link to comment
Share on other sites

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

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...