Transitions vs Animations
A transition animates between two states (start and end), usually triggered by an event like :hover. A CSS animation, defined with @keyframes, can have many steps, run automatically, and repeat without any trigger at all.
A Basic Keyframe Animation
<style>
@keyframes bounce {
0% { transform: translateY(0); }
50% { transform: translateY(-20px); }
100% { transform: translateY(0); }
}
.ball {
width: 40px;
height: 40px;
border-radius: 50%;
background: crimson;
animation: bounce 1s ease-in-out infinite;
}
</style>
<div class="ball"></div>animation Shorthand Parts
| Part | Purpose |
|---|---|
| name | The @keyframes name to run |
| duration | How long one cycle takes |
| timing-function | The speed curve, e.g. ease, linear |
| delay | How long to wait before starting |
| iteration-count | How many times to repeat, or infinite |
| direction | normal, reverse, alternate, or alternate-reverse |
Using Percentages in @keyframes
@keyframes can define as many steps as needed using percentages from 0% to 100%, giving fine control over multi-stage animations. from and to are shorthand for 0% and 100%.
Multi-Step Animation
<style>
@keyframes pulse-color {
0% { background: steelblue; }
50% { background: #764ba2; }
100% { background: steelblue; }
}
.banner {
padding: 20px;
color: white;
text-align: center;
animation: pulse-color 2s ease-in-out infinite;
}
</style>
<div class="banner">Pulsing background</div>Controlling Playback
animation-iteration-count controls how many times the animation runs (a number, or infinite), and animation-direction can alternate the animation back and forth instead of resetting each cycle.
Alternating Direction
.icon {
animation: spin 3s linear infinite alternate;
}animation-fill-mode
By default, an element reverts to its original styles after an animation ends. animation-fill-mode: forwards keeps the styles from the last keyframe instead, useful for entrance animations that shouldn’t reset.
Respect Reduced Motion
Some users prefer reduced motion due to vestibular disorders. Wrap non-essential animations in @media (prefers-reduced-motion: no-preference) so they’re skipped for users who have requested reduced motion in their OS settings.
Best Practice
Use transitions for simple, event-triggered state changes, and reserve @keyframes animations for looping or multi-step effects that need to run independently of user interaction.