CSS animations allow developers to create complex, multi-step animated sequences using @keyframes rules without relying on JavaScript animation libraries.
An animation connects an @keyframes sequence definition to an HTML element:
/* 1. Define Keyframes Sequence */
@keyframes pulseGlow {
0% {
transform: scale(1);
box-shadow: 0 0 0 0 rgba(56, 189, 248, 0.7);
}
50% {
transform: scale(1.05);
box-shadow: 0 0 20px 10px rgba(56, 189, 248, 0);
}
100% {
transform: scale(1);
}
}
/* 2. Attach Animation to Element */
.glowing-badge {
animation: pulseGlow 2s infinite ease-in-out;
}
Key animation properties:
animation-name: Matches the identifier declared in @keyframes.animation-duration: Time required to complete one cycle (2s).animation-iteration-count: Number of playback loops (1, 3, infinite).animation-direction: Direction flow (normal, reverse, alternate).animation-fill-mode: How styles apply before/after playback (forwards, backwards, both).flowchart LR
A["0% (Initial Keyframe)"] --> B["50% (Intermediate Keyframe)"]
B --> C["100% (Final Keyframe)"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Animations Demonstration</title>
<style>
@keyframes spinner {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.loading-spinner {
width: 40px;
height: 40px;
border: 4px solid #1e293b;
border-top: 4px solid #38bdf8;
border-radius: 50%;
animation: spinner 1s linear infinite;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<h2>Infinite CSS Loading Spinner</h2>
<div class="loading-spinner"></div>
</body>
</html>
@keyframes for multi-step or continuous looping animations: Use transitions for simple A-to-B state changes, and keyframe animations for complex loops or spinners.prefers-reduced-motion media queries: Disable heavy animations for users who have requested reduced motion in their OS preferences.animation-fill-mode: forwards: Retains the final keyframe visual styles when an animation finishes playing.Write an @keyframes fadeIn rule animating opacity from 0 at 0% to 1 at 100%!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.