Parallax - Perspective
Create parallax animation as the user scrolls, via CSS perspective, transform-style and transform 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
/* Create containment and set scroll zone */
html {
overflow-y: hidden;
}
body {
overflow-x: clip;
overflow-y: scroll;
height: 100vh;
}
/* Aligns content element over the media element */
.parallax-container {
height: 100vh;
display: grid;
grid-template: "container";
place-items: center;
place-content: center;
text-align: center;
& > * {
grid-area: container;
}
}
/* Only apply if the user did NOT request reduced motion */
@media (prefers-reduced-motion: no-preference) {
/* Set the perspective for the "3D" of the parallax on the scrolling body */
body {
perspective: 1px;
}
/* Set the parallax container as the "stage" */
.parallax-container {
transform-style: preserve-3d;
}
/* Push the image to the "back" of the stage,
and scale it up to compensate for being in the back */
.parallax-background {
transform: translateZ(-2px) scale(1.25);
}
/* Push the text "back" a little, but not as much,
and scale it up to compensate as well */
.parallax-foreground {
transform: translateZ(-1px) scale(3);
}
}
/* Note that any elements above or below the parallax component need this to make them "overlap" the parallax image */
header,
main {
position: relative;
z-index: 1;
}JS
No JS required.Baseline
CodePen
See the Pen on CodePen.