I'm checking out Svelte, and I'm finding a lot more out of the box that I would've expected.
One thing that surprised me a little bit where the amount of transition and animation tools, especially the tooling for custom transitions, and I can't quite tell from their syntax if these are functions that write CSS, or if they're functions that manipulate styles directly with a CSS-like syntax.
Are the resulting animations CSS only or not?
The short answer: CSS.
The longer answer: When a transition function is called, it returns an object with the transition object, which must include a css
method, a tick
method, or both. The tick
method is straightforward — it is called every frame (using requestAnimationFrame
, essentially) until the transition has completed, allowing you do things that are impossible just with CSS, like a typewriter effect.
The css
method works differently. Say you have a simple fade transition that returns a function like this:
css: t => `opacity: ${t}`
(This is almost exactly what the built-in fade transition does.) This function will be called multiple times with a different value of t
before the transition begins — the number of times depends on the duration of the transition — so that a set of keyframes are generated:
keyframes = [
'0% { opacity: 0 }',
'10% { opacity: 0.1 }',
'20% { opacity: 0.2 }',
// ...
];
Those keyframes are then joined together into a CSS animation and applied to the element.
In that simple example, it might seem over-engineered — after all, we could just go from 0% { opacity: 0 }
to 100% { opacity: 1 }
. But it gives us the power to build custom transitions with easing functions that aren't normally available in CSS animations, all without resorting to manipulating styles in JavaScript (which must happen on the main thread, creating a common source of jank.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With