CSS Keyframes: Bending the Timeline
If CSS Transitions are a straight line from point A to point B, `@keyframes` is a roller coaster. Keyframes allow you to define intermediate steps, control state retention, and loop behaviors to create true motion design on the web.
Anatomy of a Keyframe
To use keyframes, you first define the timeline rule using @keyframes [name], and then you bind it to an element using the animation shorthand (or individual animation-* properties).
You can use from (0%) and to (100%) for simple two-step animations. For more complex sequences, you use percentages to dictate exactly what the CSS values should be at that point in time during the animation's total duration.
Animation Fill Mode
One of the most common issues developers face is that when an animation completes, the element instantly reverts to its initial CSS state. This is where animation-fill-mode comes in.
- none (default): The element goes back to its normal state.
- forwards: The element retains the styling from the last keyframe (100% or `to`).
- backwards: The element applies the styles of the first keyframe (0% or `from`) immediately, even before the delay expires.
- both: Follows the rules for both forwards and backwards.
Performance Rules
With great power comes great responsibility. Heavy animations can tank framerates on mobile devices. When writing your @keyframes, prioritize animating transform and opacity. Avoid animating width, left, or margin, as they force the browser to recalculate the page layout at 60 frames per second.
Advanced: Multiple Animations+
You can apply multiple keyframes to a single element by comma-separating them:animation: slideIn 1s forwards, pulseColor 2s infinite;. This keeps your keyframes modular and reusable!
❓ Frequently Asked Questions
Can I use variables inside @keyframes?
Yes! CSS Custom Properties (variables) work perfectly inside keyframes. This allows you to create dynamic animations where the values are controlled by variables defined in Javascript or CSS classes.
Why isn't my keyframe animation working?
Check the spelling of your animation-name. It is case-sensitive! Also, ensure your element has `display: block` or `inline-block` if you are trying to transform it; `inline` elements like spans ignore transforms.
