CSS Transitions
A transition animates a property change over a set time. A change that would snap instead plays smoothly from the old value to the new one.
A button that fades to its hover colour
The transition names background-color and a half second duration. On hover the button colour plays to green instead of snapping.
button {
transition: background-color 0.5s;
}
button:hover {
background-color: green;
}Padding that grows on hover
The box starts with 10 pixels of padding. On hover the padding grows to 30 pixels, and the transition animates the growth.
.box {
transition: padding 0.4s;
padding: 10px;
}
.box:hover {
padding: 30px;
}A timing keyword in the shorthand
The shorthand can carry a timing keyword after the duration. The keyword ease-in-out starts the change slowly, speeds it up, then slows it again.
#demo {
transition: color 0.3s ease-in-out;
}
#demo:hover {
color: red;
}Example
button {
transition: background-color 0.5s;
}
button:hover {
background-color: green;
}
.box {
transition: padding 0.4s ease-in-out;
padding: 10px;
}
.box:hover {
padding: 24px;
}Key points
- transition-property names the property that animates.
- transition-duration sets how long the animation takes.
- A duration can be written in seconds, like 0.5s, or in milliseconds.
- Only properties with in-between values can animate, and display cannot.
- The word all can stand in for a property list in a transition.
- Naming the properties is the steadier habit than using all.
In this example, the button rule sets a transition on its background colour. The hover rule sets the green end colour, and the colour plays over half a second. The box rule sets a transition on padding with a timing keyword. The hover rule grows the padding, and the growth animates over 0.4 seconds.
Note
A timing keyword like ease-in-out shapes the speed curve of a transition.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does a transition need so a hover change plays smoothly?