Skip to main content

Command Palette

Search for a command to run...

[HTML&CSS] Tutorial for Making <Scroll to Top> Button on Your Web Site

Updated
2 min read
[HTML&CSS] Tutorial for Making <Scroll to Top> Button on Your Web Site
L

Computer Science Enthusiast with a Drive for Excellence | Data Science | Web Development | Passionate About Tech & Innovation


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.

https://www.w3schools.com/howto/howto_js_scroll_to_top.asp

More from this blog

Jay's Dev Blog

90 posts

Consistency is what transforms average to excellence.