How to create: a button to return to the top of the page

Learn how to use CSS to create a 'scroll back to top' button.

Try It Yourself

How to create a scroll to top button

Step 1 - Add HTML:

Create a button that, when clicked, will take the user to the top of the page:

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

Step 2 - Add CSS:

Set the button's style:

#myBtn {
  display: none; /* Defaults to hidden */
  position: fixed; /* Fixed/sticky positioning */
  bottom: 20px; /* Positions the button 20px from the bottom of the page */
  right: 30px; /* Positions the button 30px from the right edge of the page */
  z-index: 99; /* Ensures it does not overlap */
  border: none; /* Removes the border */
  outline: none; /* Removes the outline */
  background-color: red; /* Sets the background color */
  color: white; /* Text color */
  cursor: pointer; /* Adds a mouse pointer when hovering */
  padding: 15px; /* Some inner padding */
  border-radius: 10px; /* Rounded corners */
  font-size: 18px; /* Increases the font size */
}
#myBtn:hover {
  background-color: #555; /* Adds a dark gray background when the mouse hovers */
}

Step 3 - Add JavaScript:

// Get the button:
let mybutton = document.getElementById("myBtn");
// Show the button when the user scrolls down 20px from the top of the document
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    mybutton.style.display = "block";
  }
    mybutton.style.display = "none";
  }
}
// Scroll back to the top of the document when the user clicks the button
function topFunction() {
  document.body.scrollTop = 0; // For Safari
  document.documentElement.scrollTop = 0; // Suitable for Chrome, Firefox, IE, and Opera browsers
}

Try It Yourself