Table of contents
Introduction
In this article, I will talk about how to make a top button on your website, and how to make it to be scrolled smoothly.
This tutorial doesn't introduce JavaScript code. Only HTML & CSS. You may go to the bottom of this page where I put the tutorial with JavaScript code.
Making Top Button
Since it is a button, we need an <a> element outside, then we can put an <img> element inside the <a> element.
<div>
<a>
<img></img>
</a>
</div>
Then, we can start writing some code
<!-- TOP BUTTON -->
<div>
<a href="#site-header" id="top-button">
<img src="src/assets/images/top-button.png" alt="Top Button" />
</a>
</div>
html {
scroll-behavior: smooth;
}
#top-button {
position: fixed; /* IMPORTANT */
right: 30px;
bottom: 30px;
width: 40px;
}
#top-button:hover {
/* your code */
}
href="#site-header"
is used to specify where to go when the button is clicked. In this example, the top button will direct users to the site header.
It is very important to put position: fixed;
because the top button must not move although users scroll up or down the page.
Then, place the button where you want. Simply do it by giving CSS properties like top, bottom, right, and left.
To make the scroll more smooth. You can give scroll-behavior: smooth;
to the html
element.
Then, you may also add some more features, such as style changes when there is a hover event occurring.
Additional Comment
This is not the only way to make the top button. You can refer to this tutorial, too.