Keyframe wildcards example: Step-by-step
In this tutorial, we'll build the Keyframe wildcards example step-by-step.
This example is rated 1/5 difficulty, which means we'll spend some time explaining the Motion APIs that we've chosen to use (and why), and also any browser JavaScript APIs we encounter that might be unfamiliar to beginners.
Introduction
The Wildcard Keyframes example shows how to create interruptible hover animations using Motion's wildcard keyframe feature.
A "wildcard" keyframe is any keyframe that is null
.
When the initial keyframe is null
, Motion will use the current value of the property as the starting point. This allows even keyframe animations to be interruptible, unlike CSS keyframes.
Get started
Let's start with a basic component:
export default function WildcardKeyframes() {
return (
<div
style={{
width: 100,
height: 100,
backgroundColor: "#c678dd",
borderRadius: 5,
}}
/>
)
}
Let's animate!
Import from Motion
First, we'll import Motion:
import * as motion from "motion/react-client"
Creating the wildcard animation
First, let's create a basic hover animation with wildcard keyframes:
<motion.div
style={box}
whileHover={{
scale: [null, 1.1, 1.6],
transition: { duration: 0.5 },
}}
transition={{
duration: 0.3,
ease: "easeOut",
}}
/>
The scale
array starts with null
, which means "use whatever the current scale value is". The animation then progresses through two stages: first from the current value to 1.1
, then from 1.1
to 1.6
.
Controlling keyframe timing
Now, let's add precise control over when each keyframe occurs. By default, keyframes are evenly spaced throughout the duration of the animation.
By adding a times
array, we can control the exact timing of each keyframe:
<motion.div
style={box}
whileHover={{
scale: [null, 1.1, 1.6],
transition: {
duration: 0.5,
times: [0, 0.6, 1],
ease: ["easeInOut", "easeOut"],
},
}}
transition={{
duration: 0.3,
ease: "easeOut",
}}
/>
The times
array gives us fine-grained control:
0
: Start from the current scale (ournull
value)0.6
: Reach scale of1.1
at 60% of the animation1
: Finish at scale1.6
at the end of the animation
We can also specify different easing functions for each segment:
"easeInOut"
for the first segment (current scale to1.1
)"easeOut"
for the second segment (1.1
to1.6
)
Conclusion
In this tutorial, we learned how to:
- Create interruptible hover animations using wildcard keyframes
- Define multi-step animations with precise timing control
- Use different easing functions for different segments of an animation
- Create smooth transitions back to the initial state
Tutorial Project
We're currently working on adding a tutorial for every example on the Motion Examples website. So far, 12% of examples have a tutorial.