DEV Community

Cover image for Parallax using scroll driven animations
codingjlu
codingjlu

Posted on

5

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.)

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more