How to make a Scroll to Top Button in HTML & CSS

SCROLL to TOP Button Complete CODE:

<!DOCTYPE html>

<html>

<head>

<style>

#myBtn {

  display: none;

  position: fixed;

  bottom: 20px;

  right: 30px;

  z-index: 99;

  border: none;

  outline: none;

  background-color: red;

  color: white;

  cursor: pointer;

  padding: 15px;

  border-radius: 10px;

}

 

#myBtn:hover {

  background-color: #555;

}

</style>

</head>

<body>

 

<button onclick=”topFunction()” id=”myBtn” title=”Go to top”>Top</button>

 

<div style=”background-color:black;color:white;padding:30px”>Scroll Down</div>

<div style=”background-color:lightgrey;padding:30px 30px 2500px”>This example demonstrates how to create a “scroll to top” button that becomes visible when the user starts to scroll the page.</div>

 

<script>

// When the user scrolls down 20px from the top of the document, show the button

window.onscroll = function() {scrollFunction()};

 

function scrollFunction() {

    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {

        document.getElementById(“myBtn”).style.display = “block”;

    } else {

        document.getElementById(“myBtn”).style.display = “none”;

    }

}

 

// When the user clicks on the button, scroll to the top of the document

function topFunction() {

    document.body.scrollTop = 0;

    document.documentElement.scrollTop = 0;

}

</script>

 

</body>

</html>