Episode 4 of 13
Keyframes
Create multi-step animations with @keyframes — define animation stages and apply them to elements.
Keyframes
Transitions handle simple A → B changes. For multi-step, complex animations, you need @keyframes. Keyframe animations let you define multiple stages and animate through them automatically.
Defining a Keyframe Animation
@keyframes slideIn {
from {
transform: translateX(-100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
Applying the Animation
.element {
animation-name: slideIn;
animation-duration: 0.6s;
}
from/to vs Percentages
/* from/to — simple two-stage animation */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
/* Percentages — multi-stage animation */
@keyframes bounce {
0% { transform: translateY(0); }
30% { transform: translateY(-30px); }
50% { transform: translateY(0); }
70% { transform: translateY(-15px); }
100% { transform: translateY(0); }
}
from = 0% and to = 100%. Use percentages when you need more than two stages.
Animation Properties
| Property | What It Controls | Example Values |
|---|---|---|
animation-name | Which @keyframes to use | slideIn, bounce |
animation-duration | How long one cycle takes | 0.5s, 2s |
animation-delay | Wait before starting | 0.3s, 1s |
animation-timing-function | Speed curve | ease, linear |
animation-iteration-count | How many times to repeat | 1, 3, infinite |
animation-direction | Forwards, backwards, or alternating | normal, alternate |
animation-fill-mode | State before/after animation | forwards, both |
animation-play-state | Pause or play | running, paused |
Practical Examples
Fade In & Slide Up
@keyframes fadeSlideUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.card {
animation: fadeSlideUp 0.5s ease;
}
Pulse Effect
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
}
.notification-badge {
animation: pulse 2s ease-in-out infinite;
}
Loading Spinner
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid #eee;
border-top-color: #3498db;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
Transitions vs Keyframes
| Feature | Transitions | Keyframes |
|---|---|---|
| Stages | Two (start → end) | Unlimited (0% → 100%) |
| Trigger | Requires state change | Runs automatically or on class add |
| Looping | No built-in loop | infinite looping |
| Complexity | Simple | Complex multi-stage |
| Use case | Hover effects, toggles | Loading animations, entrance effects |
Key Takeaways
@keyframesdefine named animations with multiple stages- Use
from/tofor simple two-stage or percentages for multi-stage - Apply with
animation-nameandanimation-durationat minimum - Keyframes can loop, alternate, and be paused — far more flexible than transitions
- Ideal for entrance effects, loading spinners, and continuous animations