Transitions
Transitions are an easy to use CSS feature that can create simple effects, both subtle and not so subtle.
A transition is triggered when the state of an element changes. Most commonly that means when an element becomes :hover
or :active
. Transitions can also be triggered by the addition or removal of a CSS class (i.e. via JavaScript).
Transition Settings
There are four properties for defining transitions.
Property | Usage |
transition-property |
The CSS property or properties that are going to change |
transition-duration |
How long the effect(s) will take |
transition-timing-function |
The type of motion curve(s) to use. The default is linear . Other options include ease-in , ease-out , and ease-in-out . |
transition-delay |
If for some reason you want a delay before the effect happens |
There is also a shorthand transition
property for setting all of these at once.
One Caveat
One key thing to remember when using transitions is that they only apply to the state you're transitioning to.
input ~ div {
color: lightgray;
border: 2px solid lightgray;
}
input:checked ~ div {
color: red;
border: 2px solid red;
transition-property: color, border-color;
transition-duration: .6s, .6s;
}
So if, for example, you want a transition to happen when an element both gets and loses :hover
, you must include transition properties for both states.
input ~ div {
color: lightgray;
border: 2px solid lightgray;
transition-property: color, border-color;
transition-duration: .6s, .6s;
}
input:checked ~ div {
color: red;
border: 2px solid red;
transition-property: color, border-color;
transition-duration: .6s, .6s;
}
What We Can Animate
Not all CSS properties are animatable. For example, the browser can't animate the change between display: block
and display: flex
. In general though, most properties that can accept numeric values are animatable. The MDN documentation for most CSS properties will state whether that property supports animation. More concisely, MDN also maintains a list of currently animatable properties.
Here are some examples!