CSS Advanced: Variables, Motion and Modern CSS
Keyframe Animations
In this lesson you will
- Define an animation with @keyframes
- Apply it with the animation shorthand
- Control repeat count, direction and fill mode
Introduction
A transition needs a trigger, like a hover. A keyframe animation can start by itself, loop forever, and pass through many steps. It is how loading spinners, pulsing buttons and entrance effects are made.
Step 1: describe the animation
@keyframes gives the animation a name and lists what the element looks like at points in time, using from and to, or percentages.
HTML
@keyframes fade-in {
from { opacity: 0; transform: translateY(12px); }
to { opacity: 1; transform: translateY(0); }
}Step 2: apply it
Use the animation properties on an element.
Press Run again to replay it. The shorthand is animation: name duration timing-function delay iteration-count direction fill-mode.
Quick quiz
What does @keyframes do?
Looping and direction
animation-iteration-count: infiniterepeats forever.animation-direction: alternateplays forwards, then backwards, which gives a smooth back-and-forth.
Several steps with percentages
Fill mode
By default an element snaps back to its normal style when the animation ends. animation-fill-mode: forwards keeps the final keyframe. backwards applies the first keyframe during a delay.
HTML
animation: fade-in 1s ease-out 0.5s both;both is a handy shortcut. It applies the first keyframe during the delay and keeps the last one after the end.
Quick quiz
Which setting makes an animation repeat forever?
Use animation kindly
Do not animate everything. Keep motion short and meaningful, avoid flashing, and wrap looping animations in a prefers-reduced-motion check so people who dislike motion can opt out.
Try it yourself
Make a pulsing "Live" badge. Create a @keyframes blink that changes the opacity from 1 to 0.3, and apply it with infinite alternate.
Summary
@keyframes name { ... }defines the steps, andanimationapplies them.infiniteloops,alternategoes back and forth,bothkeeps the start and end states.- Prefer animating
transformandopacity, and respect reduced motion.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading