CSS transitions allow to smoothly go from one element’s state to another. How it works is that individual properties are animated from an initial to a final state.
You can define:
transition-property
: which properties to animatetransition-duration
: how long the animation laststransition-timing-function
: how the intermediate states are calculatedtransition-delay
: to start the animation after a certain amount of time
You can set each CSS property individually, or use the shorthand version: transition
. In that case, only the duration is mandatory.
Keep in mind that a transition is a specific kind of animation, where there’s only a start and an end state.
Quick example
Transitions are often used on hover states.
Instead of the hover CSS rules being instantaneous, both the background and the text colors are slowly animated.
transition-duration
A transition’s duration is the only CSS property needed to create a transition. It can either be set in seconds 2s
or milliseconds 100ms
.
If you want your transition to last half a second, you can either write 0.5s
or 500ms
. Depending on how fast you want your transitions to be, one unit might be easier and/or quicker to write.
transition-property
Only 1/3 of CSS properties can be animated. Mozilla has a complete list.
By default, the transition-property
property has a value of all
, which simply means it will animate all possible properties.
You can decide to only animate 1 or several properties.
The border
property is fully animatable and allows to easily visualize the slow (2 seconds) transition.
transition-timing-function
The timing function determines how each property’s value is calculated during the transition.
By default, the transition is eased: it accelerates at the start and slows down at the end.
You can meaning that the transition will happen at a constant speed. Timing functions can make the transition accelerate and/or slow down.
The easiest way to visualize timing functions is by altering position properties, like left
.
Ease: slow start, fast middle, slow end
Linear: constant speed
Ease In: slow start, fast end
Ease Out: fast start, slow end
Ease In Out: like ease, but with more pronounced acceleration/deceleration curves
Keep in mind that all transitions take the same amount of time (1 second).
If you want to visualize how other timing functions work, check out this Easing Functions Cheat Sheet.
cubic-bezier
If all these pre-defined timing functions don’t suit you, you can write your own using cubic bezier functions.
The website cubic-bezier.com is a simple tool to visually write your own curves.
transition-delay
A delay will define how long the transitions has to wait before actually starting.
Like transition-duration
, you can either use seconds s
or milliseconds ms
.