CSS Transitions and Animations
CSS transitions and animations add movement without JavaScript. A transition smoothly changes a property when its value changes, such as on hover. An animation runs a sequence defined with @keyframes, and can loop on its own.
CSS Transitions
List the property, duration and easing. Transitions work best with transform and opacity, because browsers animate them smoothly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSS Example</title>
<style>
.card {
width: 200px; padding: 24px; background: white; border-radius: 12px;
box-shadow: 0 2px 6px rgb(0 0 0 / 15%);
transition: transform 0.25s ease, box-shadow 0.25s ease;
font-family: sans-serif;
}
.card:hover { transform: translateY(-8px); box-shadow: 0 12px 24px rgb(0 0 0 / 20%); }
body { background: #f1f5f9; padding: 30px; }
</style>
</head>
<body>
<div class="card">Hover to lift me</div>
</body>
</html>Transform Functions
- translate(x, y): move
- scale(1.2): grow or shrink
- rotate(45deg): turn
- skew(10deg): slant
- Combine them: transform: translateX(20px) rotate(10deg)
Keyframe Animations
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSS Example</title>
<style>
@keyframes spin { to { transform: rotate(360deg); } }
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }
.loader { width: 40px; height: 40px; border: 5px solid #e5e7eb; border-top-color: #2563eb; border-radius: 50%; animation: spin 1s linear infinite; }
.dot { width: 20px; height: 20px; background: crimson; border-radius: 50%; animation: pulse 1.5s ease-in-out infinite; margin-top: 20px; }
</style>
</head>
<body>
<div class="loader"></div>
<div class="dot"></div>
</body>
</html>Respecting Reduced Motion
Some users get dizzy from motion and turn it off in their system settings. The prefers-reduced-motion media query lets you calm animations for them.
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; transition: none !important; }
}Frequently asked questions
What is the difference between CSS transition and animation?
A transition animates between two states when a value changes, usually triggered by hover or a class. An animation uses @keyframes, can have many steps and can run and loop by itself.
Which CSS properties are best to animate?
transform and opacity, because the browser can animate them without recalculating layout, which keeps motion smooth.
How do I make a CSS animation loop forever?
Set animation-iteration-count: infinite, or add infinite to the animation shorthand.