CSS Transitions: Smooth Hover and State Changes
When a property changes, for example because a button is hovered, the new value normally appears instantly. A transition tells the browser to animate from the old value to the new one over a short time. A small, quick transition makes an interface feel responsive; a slow one makes it feel sluggish.
The four parts
.button {
background: #0e7490;
transition: background-color 200ms ease-out;
}
.button:hover { background: #155e75; }
The transition shorthand combines:
- Property: what to animate (
background-color,transform,opacity), orall. - Duration: how long, in
msors. Interface feedback usually feels right between 100 and 300 milliseconds. - Timing function: the speed curve.
ease(the default) starts quickly and slows down;linearis constant;ease-outdecelerates into the final value, which suits things entering or reacting. - Delay: an optional wait before starting.
Separate several transitions with commas: transition: opacity 150ms, transform 300ms ease-out;.
The transition goes on the element's base rule, not the :hover rule, so it runs in both directions: on hover and when the pointer leaves. The example reads the transition settings back from the browser and prints them. Hover the button in the preview to see the effect.
Expected page text
Hover me property: background-color, transform duration: 0.2s, 0.15s timing: ease-out, ease
What can be animated
Properties with in-between values can transition: colors, lengths, opacity, transform. Properties without in-between values, like display or font-family, switch instantly. For smooth performance, prefer animating transform and opacity. The browser can usually handle them without recalculating the layout, whereas animating width or top makes it redo layout on every frame.
Respect reduced motion
Some people get dizzy or distracted by movement and turn on a reduce-motion setting. Honor it:
@media (prefers-reduced-motion: reduce) {
* { transition-duration: 0.01ms !important; }
}
Small color fades are generally fine, but sliding panels and zooming cards should be calmed down.
Transitions versus animations
Transitions animate between two states when something changes. For multi-step or looping motion that runs on its own, CSS has @keyframes animations, a separate feature built on the same timing ideas.
Summary
transition: property duration timing-function delayon the base rule.- Keep interface transitions short, around 100 to 300 ms.
- Prefer
transformandopacity, and respectprefers-reduced-motion.
Quiz: Transitions