How to Create a “Scroll Back to Top” Button With CSS

Providing an easy and seamless user experience is essential to keep visitors engaged and on your site.

One common usability feature is the “Scroll Back to Top” button, which appears when a user scrolls down a long page and provides a convenient way to quickly return to the top.

In this tutorial, we’ll show you how to create this button using CSS.


HTML Structure

To get started, we need to create a button that will be visible when the user scrolls down the page. Here’s an example of the HTML structure you’ll need:

<a href="#" id="scroll-top">
  <i class="fa fa-angle-up"></i>
</a>

In this example, we use an anchor tag with an ID of “scroll-top.”

This allows us to target the button using CSS. The button contains an icon from Font Awesome, but you can use any icon or text that you prefer.

CSS Styles

Next, we’ll add the CSS styles for the button.

To make it hidden by default, we’ll set its position to absolute and hide it using the opacity property.

When the user scrolls down the page, the button will become visible.

#scroll-top {
  position: fixed;
  bottom: 30px;
  right: 30px;
  opacity: 0;
  transition: all 0.5s;
}

#scroll-top:hover {
  opacity: 1;
}

In this example, we use a fixed position to make sure the button stays in the same place as the user scrolls.

The button is positioned 30px from the bottom and right of the page. The transition property provides a smooth animation when the button becomes visible.

JavaScript

Finally, we need to add some JavaScript to make the button appear when the user scrolls down the page.

Here’s an example:

window.onscroll = function() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("scroll-top").style.opacity = "1";
} else {
document.getElementById("scroll-top").style.opacity = "0";
}
};

In this example, we use the onscroll event to detect when the user is scrolling.

If the user has scrolled down more than 20 pixels, the button becomes visible. If the user scrolls back up, the button disappears.


Conclusion

With just a few lines of code, you can create a “Scroll Back to Top” button that enhances the user experience on your site.

Whether you’re a website owner or a developer, this simple feature is a great way to provide a convenient and seamless experience for your visitors.

Try it out and see the difference it can make!