Introduction
CSS animations allow you to create continuous, repeatable, and complex motion effects without JavaScript. Unlike transitions, which require a state change (like hover), animations can run automatically.
In this chapter, you will learn:
- Difference between transitions and animations
- How to use
@keyframes - Animation properties (duration, iteration, direction)
- Creating spinners, bounce effects, and slide-ins
- Performance and accessibility best practices
Transitions vs Animations
| Feature | Transition | Animation |
|---|---|---|
| Trigger | Needs trigger (hover, focus) | Runs automatically |
| Complexity | Simple (A to B) | Complex (Keyframes) |
| Control | Limited | Powerful (loop, pause, reverse) |
The @keyframes Rule
Animations are defined using @keyframes, which describes the styles at specific points.
@keyframes fadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}Applying it to an element:
.box {
animation-name: fadeIn;
animation-duration: 1s;
}Animation Properties
Iteration Count
Controls how many times adjustments run.
animation-iteration-count: infinite; /* loops forever */Animation Direction
animation-direction: alternate; /* Forward then backward */Shorthand Property
/* name duration timing delay iteration direction fill-mode */
animation: fadeIn 1s ease-in-out 0s infinite alternate;Real-World Examples
1. Infinite Loading Spinner
.loader {
width: 40px;
height: 40px;
border: 4px solid #ccc;
border-top-color: #007bff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}2. Bounce Effect
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-20px); }
}
.icon {
animation: bounce 1s infinite;
}3. Slide-In Fade Animation
@keyframes slideIn {
from { transform: translateX(-50px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.card {
animation: slideIn 0.5s ease forwards;
}Performance & Accessibility
Best Practices
- Animate
transformandopacity(GPU optimized) - Avoid animating
width,height, ormargin - Use
prefers-reduced-motionmedia query
Reduced Motion Code
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; }
}Chapter Summary
In this chapter, you learned:
- How to define animations with
@keyframes. - Controlling animation flow with duration, iteration, and direction.
- Building loaders, bounce effects, and slide-ins.
- Optimizing for performance and accessibility.
You now understand how to create smooth, controlled, professional animations using pure CSS.