Parallax - Scroll Animation
Create parallax animation as the user scrolls, via CSS scroll-driven-animations only, no JS required.
Demo
Hero Text
Supporting text,
Really quite fascinating...
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>Hero Text</h1>
<p>Supporting text,<br>
Really quite fascinating...</p>
</div>
</section>CSS
/* Only apply if the user did NOT request reduced motion */
@media (prefers-reduced-motion: no-preference) {
/* Create 3D animations */
/* Reduce the parallax "speed" by reducing the Y animation from/to "range".
From -10% to -90% would create a much faster parallax effect.
*/
/* Animation for background image */
@keyframes parallax-image {
from {
translate: -50% -50% 0;
}
to {
translate: -50% -75% 0;
}
}
/* Animation for foreground text */
@keyframes parallax-text {
from {
translate: -50% 150% 0;
}
to {
translate: -50% -250% 0;
}
}
/* Create 3D animation context */
.parallax-container {
view-timeline: --parallax-on-scroll;
& > div {
/* Initial position, to allow animation*/
position: fixed;
top: 50%;
left: 50%;
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;
}
}
/* The header and main elements need this to "overlap" the parallax background image */
header,
main {
position: relative;
z-index: 1;
}JS
No JS required.Baseline
CodePen
See the Pen on CodePen.