First, find an image to use as your button
SVG images are great because since they are vector images, they can be resized without any loss of resolution. PNG and WEBP images are also fine, because they support transparency, so the background can show through any empty spaces. Color it to suit your style. You can download this one to play around with, if you like.
Next, let's style the button with CSS
Give the button style a unique identifier name
Be sure there are no other elements using the same identifier in your stylesheet or html code.
Remove any previous styles
Just in case you have declared image styles elsewhere in your stylesheet.
Hide the image by default
We'll use javascript later to make it re-appear once the user scrolls past a certain set point.
Position it near the bottom right corner and make sure it stays there
Adjust the sizes to suit your own layout.
bottom: 2rem;
right: 1rem;
Fade it a little so any page elements still show through
Ensure that it is always on top of any other elements
Close the styled element
Easy enough to forget!
Put all the CSS together:
This is how it should appear in your stylesheet.
unset: all;
position:fixed;
bottom: 2rem;
right: 1rem;
opacity: .5;
}
Now, add some html to your page code
Put it at the top so you can find it later.
The button will always appear in the bottom right corner no matter where you place the code in your html.
Create the div
Insert your image
Call the image and size it to fit your layout.
Close the div
Does this make me sound forgetful? Well, it should, because I am.
Put all the html together
This is how it should appear in your html code.
Finally, write the javascript
Create a separate file that uou call with a <script src="[path to the javascript file]"></script>, or add it inside a <script> [javascript code] </script> tag before the </body> tag at the end of your html.
Get the button based on the identifier
When the user scrolls down 20px from the top of the page, show the button
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else { mybutton.style.display = "none";}
}
And lastly, the function that returns the user to the top of the page
We use separate calls to accommodate various (older) browsers.
document.body.scrollTop = 0;
// For Safari
document.documentElement.scrollTop = 0;
// For Chrome, Firefox, IE and Opera
}