blog-details

Introduction to Scroll-Driven Animations with CSS scroll() and view()

12/21/2024

Ayush Shah

If you are working as a front-end developer, then you might have heard about scroll-based animation, and you might have used libraries like GSAP to do the same. But as of now (Sept 2024), we have CSS-only scroll-driven animation, so you don’t have to write JavaScript code for it anymore.


Well, if you are not familiar with scroll-based animation, imagine you open a website, and when you scroll, the elements on the webpage move in a way that feels impressive and interactive. It's a visual treat, right?


Checkout this page

Saw that? As you scroll, you can see different types of motion that really elevate the user experience. Now, let’s get back to basics to understand how this works using CSS.

A Rotating Triangle

Let’s start with something familiar: an infinite rotating triangle. It has a keyframe animation, which is pretty common.

/*.<div class="triangle"></div> */
.triangle {
  border: 10rem solid transparent;
  border-bottom-color: #c9ff21;
  width: 0px;
  margin: auto;
  animation: rotate 5s infinite;
}

@keyframes rotate {
  to {
    rotate: y 5turn;
  }
}

Looks familiar, right? Now, let’s make some changes and see the magic!

<div class="triangle"></div>
<style>
  .triangle {
    border: 10rem solid transparent;
    border-bottom-color: #c9ff21;
    width: 0px;
    margin: auto;
    animation: 1ms rotate;
    animation-timeline: scroll();
  }

  @keyframes rotate {
    to {
      rotate: y 5turn;
    }
  }
</style>


Just a few lines of change and boom, the same animation works on scroll!

Now, you might be thinking, “When will this be useful?” and “Why use scroll-telling?” Of course, I agree that as of now, it might not be production-ready due to limited browser support. But this is to show how powerful and optimized your animations can be using just CSS. Before this, we had to rely on libraries like GSAP or Three.js, but now, for simpler animations, third-party libraries aren’t necessary.