Normally when a style changes, such as a button’s color on hover, the change is instant. A transition tells the browser to move smoothly from the old value to the new one.
<style>
.btn {
display: inline-block; padding: 12px 24px; background: #1a5276; color: #fff; border-radius: 6px;
transition: background-color 0.3s;
}
.btn:hover { background-color: #d94a00; }
</style>
<span class="btn">Hover over me</span>
Remove the transition line and press Run. The color change becomes instant.
How it is built
A transition always needs two things:
- Two states: a normal rule and a changed one, usually with
:hover,:focusor a class added by JavaScript. - A transition declaration on the normal state: which property, and how long.
.btn {
transition: background-color 0.3s; /* property, then duration */
}
Put the transition on the element’s normal rule, not only on :hover. If it is only on :hover, it animates when you enter but snaps back when you leave.
Many properties at once
Separate several with commas:
.card { transition: transform 0.2s, box-shadow 0.2s; }
What can be transitioned?
Properties with values that can be calculated between: colors, sizes, opacity, positions, transforms. Properties like display and font-family jump instantly, because there is nothing “between” block and none.
Keep it quick
The next lesson digs into the individual properties: Transition Property and Duration.