HTML Dog
Skip to navigation

CSS Transitions

Transitions allow you to easily animate parts of your design without the need for the likes of JavaScript. How dangerous.

At the most simplistic level, think of a traditional :hover state, where you might change the appearance of a link when a cursor fondles it:


a:link {
    color: hsl(36,50%,50%);
}
a:hover {
    color: hsl(36,100%,50%);
}

This creates a binary animation; a link switches from a subdued orange to a rich orange when it is hovered over.

The transition property, however, is much more powerful, allowing smooth animation (rather than a jump from one state to another). It is a shorthand property that combines the following properties (which can be used individually if you so choose):

Returning to the shorthand property, if a transition is applied like so…


a:link {
    transition: all .5s linear 0;
    color: hsl(36,50%,50%);
}
a:hover {
    color: hsl(36,100%,50%);
}

…when the link is hovered over, the color will gradually change rather than suddenly switch. The transition property here is saying it wants all properties transitioned over half a second in a linear fashion with no delay.

Targeting specific properties

While “all” can be used in transition-property (or transition), you can tell a browser only to transition certain properties, by simply plonking in the property name you want to change. So the previous example could actually include transition: color .5s ease 0, given only the color changes.

If you want to target more than one property (without using “all”), you can offer up a comma-separated list with transition-property:


a:link {
    transition: .5s;
    transition-property: color, font-size;
...

Or you can offer up a slew of rules for transitioning each property like so:


a:link {
    transition: color .5s, font-size 2s;
...

Easing

OK, so transition-timing-function (catchy!) is the least obvious fella. It effectively states how the browser should deal with the intermediate states of the transition.

It follows a cubic B├ęzier curve. Yeah. Obviously, we know all about them from infant school, but, to get down to it, at the most basic level you can use ease or linear.

ease produces a gradual acceleration at the start of the transition and a gradual deceleration at the end. linear maintains a constant speed throughout. Other values include ease-in and ease-out.