27

I am trying to create a pure 100% CSS (no jQuery) "Back to Top" button but I would like the button to show only if the visitor scrolls down the page.

Is it possible to check that with CSS somehow? So if visitor scrolled down a bit show the "Back to Top" button.

Thanks!

user3096206
  • 592
  • 3
  • 6
  • 12

1 Answers1

35

Determine by Cursor Location

One way you could do this would be to only show the .toTop element when the user is hovering over the content of the page itself, well below the header, and navigation links:

.toTop { opacity: 0; }
.toTop:hover, main:hover + .toTop { opacity: 1; }

You can see the effect here: http://jsfiddle.net/GFfbe/1/

Or, Slowly Uncover It

Alternatively, you could slowly uncover the .toTop link with another element. In the example below, I use the body's pseudo element ::before to cover up the .toTop element, and slowly reveal it as the user scrolls:

/* .toTop will appear in the left margin */
body {
    margin: 0 10em;
}

/* Positioned and sized to overlap .toTop */
body::before {
    content: "";
    background: white;
    position: absolute;
    bottom: 0; left: 0;
    width: 100%; height: 5em;
}

/* Positioned, so body::before goes behind it */
main {
    position: relative;
}

/* Attached to viewport at bottom left */
.toTop {
    z-index: -1;
    position: fixed;
    bottom: 1em; left: 1em;
}

You can see this effect here: http://jsfiddle.net/GFfbe/2/

Community
  • 1
  • 1
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 1. "Back to top" appear even we don't need a scroll. 2. If we scroll a little bit, we could see a half of "Back to top" button. http://jsfiddle.net/GFfbe/8/ – EAndreyF Jul 29 '15 at 08:17
  • 2
    Smart idea. Only negative i find with this trick is that it won't work with mobile users, like all the other `:hover` techniques . . – Jo E. Apr 02 '16 at 09:46
  • @JoE.: why won't it work with on mobile devices? `:hover` seems to enjoy universal support by mobile browsers: https://caniuse.com/#search=%3Ahover – Hassan Baig May 03 '18 at 12:10
  • 1
    @HassanBaig I think its because `hover` collides with `click` since phones can't `hover` like desktop users with a mouse cursor. So in a smartphone if you touch an image for example, the hover handler will trigger, but if you have a click handler it will trigger also. I think that was and is still the issue? – Jo E. May 03 '18 at 12:37