What is animation in CSS?
CSS animations change property values over time using @keyframes, which define the steps, and the animation property, which applies them with a duration, timing function, delay, iteration count and direction. Unlike transitions, they can run automatically, loop and have many intermediate steps without any state change.
Defining keyframes
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
The animation sub-properties
animation-name,animation-duration,animation-timing-function(ease,linear,cubic-bezier(),steps()).animation-delay,animation-iteration-count(infinite),animation-direction(alternate).animation-fill-mode:forwardskeeps the final state;bothalso applies the first frame during the delay.animation-play-state: pause and resume.- Shorthand:
animation: pulse 1.5s ease-in-out infinite;
Performance
Animate transform and opacity; they can run on the compositor without layout or paint. Animating width, height, top or margin triggers layout on every frame and causes jank.
Modern features
- Scroll-driven animations:
animation-timeline: view()orscroll()ties progress to scrolling, with no JavaScript. - View Transitions API for animating between pages and states.
@starting-stylefor entry animations fromdisplay: none.- JavaScript control with the Web Animations API (
el.animate()) andanimationendevents.
Accessibility
Respect prefers-reduced-motion: reduce, avoid flashing more than three times per second, and let users pause long-running motion.
Code example
1<style>2 body { font-family: system-ui; display: flex; gap: 24px; align-items: center; flex-wrap: wrap; }3 @keyframes pulse { 50% { transform: scale(1.12); } }4 @keyframes spin { to { transform: rotate(1turn); } }5 @keyframes slide-in { from { opacity: 0; transform: translateY(16px); } }6 .badge { background: #e11d48; color: white; border-radius: 999px; padding: 6px 12px; animation: pulse 1.4s ease-in-out infinite; }7 .spinner { width: 36px; height: 36px; border: 4px solid #e5e7eb; border-top-color: #2b4bff; border-radius: 50%; animation: spin .8s linear infinite; }8 .card { padding: 12px; border: 2px solid #0b1020; border-radius: 8px; animation: slide-in .5s ease-out both; }9 .card:nth-child(4) { animation-delay: .15s; }10 .typing { font-family: monospace; width: 13ch; white-space: nowrap; overflow: hidden; border-right: 2px solid; animation: type 2s steps(13) infinite alternate; }11 @keyframes type { from { width: 0; } }12 @media (prefers-reduced-motion: reduce) { * { animation: none !important; } }13</style>14<span class="badge">3 new</span>15<div class="spinner" role="status" aria-label="Loading"></div>16<div class="card">Slides in</div>17<div class="card">Then me</div>18<div class="typing">Hello, world!</div>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.