CSS3 transitions tutorial

The first thing you have to learn on CSS3 Transitions is the concept of CSS states. A CSS state is the condition that determines how an element is rendered within a particular time span. For example, when you have a link which changes its background color on hover, you actually have two states: the :link state and the :hover state. What happens between these two states, that is, in the time span when our link changes its background color? This is when CSS3 transitions come into play.

For example, let's consider a simple element with different styles on its normal and hover state:

#test {
 width: 100px;
 height: 100px;
 background: #d40;
 position: relative;
}
#test:hover {
 background: orange;
 width: 150px;
 height: 150px;
 left: 100px;
}

When you hover this element with your mouse, its width and height change, together with its background color and position on the page. The problem here is that the effect will happen just in a moment, like a sudden flash of light in the dark. What we want, instead, it's a gradual and progressive mutation of its CSS properties until they reach their target state on hover. In other words, we want a transition.

A CSS transition is made up of several values, but the most important are these:

  1. property: the CSS property we want to affect
  2. delay: the time span between the initial state and the target state
  3. type: the type of transition

With the transition shorthand property we can group all these values together. Unfortunately, at the moment of this writing, browsers support CSS3 transitions only through vendor prefixes, so we're going to use these prefixes together with the standard property:

#test {
 width: 100px;
 height: 100px;
 background: #d40;
 position: relative;
 -webkit-transition: background 2s ease, width 2s ease-out, height 2s ease-out, left 2s ease-out;
 -moz-transition: background 2s ease, width 2s ease-out, height 2s ease-out, left 2s ease-out;
 -o-transition: background 2s ease, width 2s ease-out, height 2s ease-out, left 2s ease-out;
 transition: background 2s ease, width 2s ease-out, height 2s ease-out, left 2s ease-out;
}

As you can see, we can affect several CSS properties by separating each group with a comma. In each group, first comes the CSS property we want to affect, then the time delay and finally the type of transition. For a complete list of values, check out the specifications. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.