Parallax - Scroll Animation
Create parallax animation as the user scrolls, via CSS scroll-driven-animations only, no JS required.
Demo
Scroll Here
Notice the text...
Scrolls differently than the background...
HTML
<section class="parallax-container">
<div class="parallax-background">
<img src="https://images.unsplash.com/photo-1472712739516-7ad2b786e1f7?crop=entropy&cs=srgb&fm=jpg&ixid=M3wzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE3NjgzNzU5NDN8&ixlib=rb-4.1.0&q=85" alt="Image of stars in the night sky" width="3000" height="2000">
</div>
<div class="parallax-foreground">
<h1>Scroll Here</h1>
<p>Notice the text...<br>
Scrolls differently than the background...</p>
</div>
</section>CSS
/* Aligns content element over the media element, makes the demo look good... */
.parallax-container {
position: relative;
height: 50vh;
overflow: clip;
place-items: center;
place-content: center;
text-align: center;
& img {
max-width: 100vw;
}
}
.parallax-foreground {
color: rgba(255, 255, 255, .85);
text-shadow: 0 0 10px rgba(0, 0, 0, .75);
text-transform: uppercase;
}
/* Only apply if the user did NOT request reduced motion */
@media (prefers-reduced-motion: no-preference) {
/* Create 3D animations */
/* Alter the parallax "speed" by reducing the "range" of the Y value's from/to:
Going from -50% to -55% would create a slower parallax effect.
Going from -10% to -90% would create a faster parallax effect.
*/
/* Animation for background image */
@keyframes parallax-image {
from {
translate: 0% -50% 0;
}
to {
translate: 0% -75% 0;
}
}
/* Animation for foreground text */
@keyframes parallax-text {
from {
translate: 0% 150% 0;
}
to {
translate: 0% -250% 0;
}
}
/* Create 3D animation context */
.parallax-container {
view-timeline: --parallax-on-scroll;
& > div {
/* Initial position, to allow animation*/
position: absolute;
top: 50%;
left: 0;
width: 100%;
/* Add timeline and range*/
animation-timeline: --parallax-on-scroll;
animation-range: normal;
}
}
/* Apply the animations */
.parallax-background {
animation: parallax-image linear both;
}
.parallax-foreground {
animation: parallax-text linear both;
}
}JS
No JS required.Baseline
CodePen
See the Pen on CodePen.