Animations with the transition property
suggest changeUseful for simple animations, the CSS transition
property allows number-based CSS properties to animate between states.
Example
.Example{
height: 100px;
background: #fff;
}
.Example:hover{
height: 120px;
background: #ff0000;
}
By default, hovering over an element with the .Example
class would immediately cause the element’s height to jump to 120px
and its background color to red (#ff0000
).
By adding the transition
property, we can cause these changes to occur over time:
.Example{
...
transition: all 400ms ease;
}
The all
value applies the transition to all compatible (numbers-based) properties. Any compatible property name (such as height
or top
) can be substituted for this keyword.
400ms
specifies the amount of time the transition takes. In this case, the element’s change in height will take 400 milliseconds to complete.
Finally, the value ease
is the animation function, which determines how the animation is played. ease
means start slow, speed up, then end slow again. Other values are linear
, ease-out
, and ease-in
.
Cross-Browser Compatibility
The transition
property is generally well-supported across all major browsers, excepting IE 9. For earlier versions of Firefox and Webkit-based browsers, use vendor prefixes like so:
.Example{
transition: all 400ms ease;
-moz-transition: all 400ms ease;
-webkit-transition: all 400ms ease;
}
Note: The transition
property can animate changes between any two numerical values, regardless of unit. It can also transition between units, such as 100px
to 50vh
. However, it cannot transition between a number and a default or automatic value, such as transitioning an element’s height from 100px
to auto
.