Titre : Parallaxe au scroll
Description : Parallaxe vertical avec 3 éléments
Code : <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Parallaxe au scroll</title> <style> /* Conteneur qui définit la zone de défilement */ .parallax-container { display: grid; grid-template-columns: 1fr; grid-template-rows: 1fr; height: 100vh; /* Ajustez selon vos besoins */ width: 100%; position: relative; overflow: hidden; } /* Base commune pour les 3 éléments superposés */ .layer { grid-area: 1 / 1; /* Force la superposition exacte */ width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-size: 2rem; font-weight: bold; will-change: transform; /* Optimisation des performances */ } /* --- VITESSES DE DÉFILEMENT CONTROLLÉES EN CSS --- */ /* 1. Vitesse Normale (suit le scroll naturel) */ .layer-normal { background: rgba(255, 0, 0, 0.2); transform: translateY(calc(var(--scroll) * -1px)); } /* 2. Vitesse Lente (avance 2 fois moins vite : coefficient 0.5) */ .layer-lent { background: rgba(0, 255, 0, 0.2); transform: translateY(calc(var(--scroll) * -0.5px)); } /* 3. Vitesse Très Lente (avance 5 fois moins vite : coefficient 0.2) */ .layer-tres-lent { background: rgba(0, 0, 255, 0.2); transform: translateY(calc(var(--scroll) * -0.2px)); } .section { height: 100vh; background-color: #979797; } .section:nth-child(2) { background-color: #5a5a5a; } .section:nth-child(3) { background-color: #868686; } </style> </head> <body> <div class="parallax-container"> <div class="layer layer-tres-lent">Élément Très Lent</div> <div class="layer layer-lent">Élément Lent</div> <div class="layer layer-normal">Élément Normal</div> </div> <div class="section">1</div> <div class="section">2</div> <div class="section">3</div> <script> // On récupère le conteneur principal const container = document.querySelector(".parallax-container"); window.addEventListener("scroll", () => { // Calcule la position actuelle du scroll par rapport au conteneur const scrolled = window.scrollY; // Met à jour la variable CSS directement sur le conteneur requestAnimationFrame(() => { container.style.setProperty("--scroll", scrolled); }); }); </script> </body> </html>
Langage de Prism :
Mettre à jour