Comment créer : un bouton pour retourner en haut de la page

Apprendre à créer un bouton "retour en haut" en utilisant CSS.

Essayez-le vous-même

Comment créer un bouton pour faire défiler vers le haut

Première étape - Ajouter HTML :

Créer un bouton qui, lorsqu'il est cliqué, emmène l'utilisateur en haut de la page :

<button onclick="topFunction()" id="myBtn" title="Aller en haut">Haut</button>

Deuxième étape - Ajouter CSS :

Set the button style:

#myBtn {
  display: none; /* It is hidden by default */
  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 */
}

Third step - 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) {
    else {
  }
    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; // Applicable to Chrome, Firefox, IE, and Opera browsers
}

Essayez-le vous-même