Transitions are great for simple state changes โ hover in, hover out. But for anything more complex โ something that loops, or has multiple steps โ you need CSS animations. Animations give you full control over what happens at each point in time.
@keyframes
Every animation starts with a @keyframes rule. This defines the sequence
of styles at different points during the animation.
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
from is the start (0%), to is the end (100%). You can also
use percentages for more steps.
Animation Name and Duration
Once you have your keyframes, apply them to an element:
.box {
animation-name: fadeIn;
animation-duration: 1s;
}
The animation-name matches the name you gave your @keyframes.
animation-duration controls how long one cycle takes.
Multiple Keyframe Steps
For more complex animations, use percentage points:
@keyframes bounce {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-30px);
}
70% {
transform: translateY(-10px);
}
100% {
transform: translateY(0);
}
}
.box {
animation-name: bounce;
animation-duration: 0.6s;
animation-iteration-count: infinite;
}
This creates a bouncing effect. The element goes up 30px, comes back down a bit, then
settles. infinite makes it loop forever.
Animation Shorthand
Like transitions, animations have a shorthand:
.box {
animation: bounce 0.6s ease infinite;
}
/* name, duration, timing-function, iteration-count */
Other animation properties you can use:
animation-delayโ wait before startinganimation-directionโnormal,reverse,alternateanimation-fill-modeโ what happens before/after (forwards,backwards)
.box {
animation: bounce 0.6s ease infinite alternate;
}
alternate makes the animation go forward, then backward, then forward again.
Combined with infinite, it creates a smooth back-and-forth motion.