CSS transitions are how you add smooth animations between two states. Instead of a button that instantly changes color on hover, a transition makes it fade smoothly. It is a small touch that makes a huge difference in how polished your site feels.
Transition Property and Duration
The simplest transition needs two things: what to animate, and how long it should take.
button {
background-color: #3498db;
transition-property: background-color;
transition-duration: 0.3s;
}
button:hover {
background-color: #2980b9;
}
When you hover the button, the background fades from blue to darker blue over 0.3 seconds. Without the transition, it would snap instantly.
Try it Yourself โTransition Timing Function
The timing function controls the speed curve of the animation. Does it start fast and slow down? Or ease in gently then speed up?
button {
transition-property: all;
transition-duration: 0.3s;
transition-timing-function: ease; /* default */
transition-timing-function: linear;
transition-timing-function: ease-in;
transition-timing-function: ease-out;
transition-timing-function: ease-in-out;
}
ease is the default โ it starts fast, slows down at the end. linear
is constant speed. ease-out is great for things entering the screen.
The Transition Shorthand
Writing all the transition properties separately gets verbose. Use the shorthand instead:
button {
transition: background-color 0.3s ease;
}
/* property, duration, timing function */
/* You can also add a delay: */
button {
transition: background-color 0.3s ease 0.1s;
}
The order is: property, duration, timing function, delay. The only required values are the property and duration โ the rest have sensible defaults.
Transitioning Multiple Properties
You can transition several properties at once:
button {
background-color: #3498db;
transform: scale(1);
transition: background-color 0.3s ease, transform 0.2s ease;
}
button:hover {
background-color: #2980b9;
transform: scale(1.05);
}
Or just use all to transition everything:
button {
transition: all 0.3s ease;
}
all is convenient, but specifying individual properties is better for
performance and control.