DEV Community

Cover image for Parallax using scroll driven animations
codingjlu
codingjlu

Posted on

Parallax using scroll driven animations

Few things are more satisfying than an immersive and beautiful parallax effect well-placed on a website. Unfortunately, the better-looking more complex effects tend to be, well, more complex (to implement), and parallax isn't an exception.

There are several approaches to creating a parallax effect, perhaps the most common is using JavaScript, where you listen for a user scroll event and update the position of a certain element accordingly. However, it's all too easy to end up with a janky and low-performance result, and making it look smooth takes a ton of work. (Yeah, there are also libraries out there, but that just adds more bloat to your app and often lacks customization.)

Then there's the CSS trick where you play with perspective and 3D translations. The issue here? Embrace it: it's hard, confusing, and doesn't always work.

With that out of the way, recently I looked into the relatively new (and as of now Chrome-only) scroll-driven animation API. This approach allows you to apply CSS animations using a scroll-based (instead of time-based) timeline, in other words, you animate stuff based on the user scrolling, without using JavaScript. You might see where this is headed: we can animate the translation of an element based on the scroll position, giving us a very straightforward and smooth effect. Is this approach necessarily better? I don't know, but it looks a lot more doable (plus, it'll be fun).

Alright, here's some actual code. Define a CSS animation...

@keyframes p-1 {
  from { transform: translateY(0) }
  to { transform: translateY(-100px) }
}
Enter fullscreen mode Exit fullscreen mode

and add it to some element:

#parallax {
  animation-name: p-1;
  animation-timeline: scroll();
  animation-timing-function: linear;
}
Enter fullscreen mode Exit fullscreen mode

Yeah. That's it. Mic drop.

All you have to do is tweak how much you translate a certain element in the animation to determine its "scroll speed".

Oh, and of course, the codepen.

Sponsored by scroll-driven animations. (Just kidding.)

Top comments (0)