CSSadvanced 8 min
Keyframe animations that run on their own: @keyframes, duration, iteration and fill mode.
How to define a multi-step animation with @keyframes and apply it with the animation property.
Loading spinners, attention-grabbing buttons and entrance effects need motion that starts by itself and can repeat. Transitions only run when a state changes, but animations run on their own.
An animation has two parts:
animation property applies them to an element:The shorthand takes the name, duration, timing function, and optional extras:
infinite or a number: how many times to repeat.alternate: play forward then backward.animation-delay: wait before starting.animation-fill-mode: forwards: keep the final state when it ends.animation-play-state: paused: pause it.@keyframes bounce goes from no offset, up 30px at the halfway point, and back to no offset..ball runs it for 1 second, smoothly, forever (infinite).@keyframes spin only has a to step, which means "from the current state, end at a full turn"..square spins once every 2 seconds at a steady pace (linear).Change infinite to 3 so the ball bounces three times and stops. Then add animation-direction: alternate to the square.
width and top, which is slow. Prefer transform and opacity.forwards, so an element snaps back after a one-time animation.@keyframes, apply with animation.transform and opacity and honour reduced-motion settings.Next: common modern layout patterns.
.dot {
animation: pulse 1.5s ease-in-out infinite;
}@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.2); }
100% { transform: scale(1); }
}<style>
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-30px); }
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.ball {
width: 40px;
height: 40px;
background: tomato;
border-radius: 50%;
animation: bounce 1s ease-in-out infinite;
}
.square {
width: 40px;
height: 40px;
background: royalblue;
margin-top: 40px;
animation: spin 2s linear infinite;
}
</style>
<div class="ball"></div>
<div class="square"></div>