I keep learning little details about scroll-driven animations!
I started this little journey thinking about if you wanted to do special styling when a page scrolled through a certain section. I thought then that in order to pass scrolling information to descendants, you’d have to do it with --custom-properties
. That’s sometimes still a decent idea, but it’s not strictly true, as those descendants can inherit a named timeline and tap into that to do styling on themselves.
Then I thought, while that’s a nice improvement, it’s still limited in the sense that only descendants can tap into a higher-up-the-DOM element’s timeline. Like an enforced parent/child situation. Turns out this isn’t true either, and again thanks to Bramus for showing me how it works.
Since we’re three-deep here on this journey, I figure calling it a series makes sense:
Fair warning all this stuff is Chrome ‘n’ friends only right now. But I’ve seen flags in both Safari and Firefox so it’s coming along.
You can have any element on the page “listen” to a scroll (or view) timeline of a totally different element.
That’s the rub.
I wrongly assumed it had to be a parent/child thing (or parent/descendant). By default, that’s true, but if you intentionally move the scope of the timeline to another element up the DOM, you can make it work for any elements.
I’ll illustrate:
Demo of that:
The idea above is that you scroll the element on the top and the element below rotates. They are sibling elements though, so this is only possibly by “hoisting” the scroll-timeline
to a higher-in-the-DOM element with timeline-scope
so that the other element can pick up on it.
My ridiculous head thought of trying to make a quiz game or some kind of unlocking puzzle with getting scroll positions just right. I proved out the idea here:
There are a bunch of abused CSS tricks in there:
- Declare a custom property with @property so it’s value can be animated
- Make a scrolling element with a
scroll-timeline
- Hoist that timeline up to a parent element
- Have the “number” element explicitly use that timeline
- Make the @keyframes animate that
<integer>
custom property - Display the number using a pseudo element and
counter()
- Use
@container style()
queries to check when the custom property is exactly the “answer” and update styling.
Phew. It all kinda leads up to that very last step where we can react to a value that came from a user scrolling. It might be a fun little project to build a bike lock number-twister thing with this.
How can we create something like this where one side is going up and the other one is coming down?
https://element-labs-35fb5d.webflow.io/
This demo should get you going!
https://scroll-driven-animations.style/demos/reverse-scroll/css/
OMG Cool. Thank you so much 😍