Transitions
A transition animates the change between two states, for example when the mouse moves over a button:
.button {
background: #17594f;
color: white;
padding: 10px 18px;
border-radius: 999px;
transition: background 0.2s ease, transform 0.2s ease;
}
.button:hover,
.button:focus-visible {
background: #0f453d;
transform: translateY(-2px);
}
List the properties that should animate and how long each takes. Add the same effect to :focus-visible so keyboard users see it too.
Keyframe animations
For motion that runs on its own, describe the steps with @keyframes and attach them with animation:
@keyframes fade-up {
from { opacity: 0; transform: translateY(16px); }
to { opacity: 1; transform: translateY(0); }
}
.card {
animation: fade-up 0.5s ease-out both;
}
.card:nth-child(2) { animation-delay: 0.1s; }
.card:nth-child(3) { animation-delay: 0.2s; }
both keeps the first frame before the animation starts and the last frame after it ends, so cards do not flash into view. For a repeating effect such as a loading spinner, add infinite.
Timing and easing
- Duration: 150–300 ms feels quick for buttons and menus; 300–600 ms suits larger elements entering the page. Longer than that usually feels slow.
- Easing:
ease-outstarts fast and slows down, which feels natural for things arriving.ease-insuits things leaving.linearis best for spinners. - You can design your own curve with
cubic-bezier(); browser developer tools have an editor for it.
Keep it smooth
Browsers can animate transform and opacity cheaply. Animating width, height, top or margin forces the browser to recalculate the layout on every frame, which can stutter on phones.
/* Slower: changes layout every frame */
.panel.open { height: 300px; transition: height 0.3s; }
/* Smoother: moves and scales without layout */
.panel { transform: scaleY(0); transform-origin: top; transition: transform 0.3s ease-out; }
.panel.open { transform: scaleY(1); }Respect reduced motion
Some people turn on "reduce motion" in their phone or computer settings because movement makes them dizzy or distracted. CSS can detect this:
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
This keeps the end result of every animation but removes the movement. Never hide important information inside an animation: the page must make sense without it. See web accessibility basics for more.
Try it yourself
In Unays Code, choose HTML, make three cards that fade up one after another and a button with a hover transition. Then turn on "reduce motion" in your device settings and check that everything still appears.
This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].