Sunday, 29 July 2012

Transitioning states in CSS3

I remember being slightly confused when I first started play-
ing around with CSS Transitions. Wouldn’t it make more
sense if the transition properties were placed in the :hover
declaration, since that’s the trigger for the transition? The an-
swer is that there are other possible states of an element be-
sides :hover, and you’ll likely want that transition to happen
on each of those without duplication.
For instance, you may want the transition to also happen
on the :focus or :active pseudo-classes of the link as well.
Instead of having to add the transition property stack to each
of those declarations, the transition instructions are attached
to the normal state and therefore declared only once.
The following example adds the same background switch to
the :focus state. This enables triggering the transition from
either hovering over or focusing the link (via the keyboard, for
example).
a.foo {
  padding: 5px 10px;
  background: #9c3;
  -webkit-transition: background 0.3s ease;
  -moz-transition: background 0.3s ease;
  -o-transition: background 0.3s ease;
  transition: background 0.3s ease;
  }
a.foo:hover,
a.foo:focus {
  background: #690;
  }


TRANSITIONING MULTIPLE PROPERTIES
Let’s say that along with the background color, we also want
to change the link’s text color and transition that as well. We
can do that by stringing multiple transitions together, sepa-
rated by a comma. Each can have their varying duration and
timing functions (fig 2.03). (Line wraps marked ».)
a.foo {
  padding: 5px 10px;
  background: #9c3;
  -webkit-transition: background .3s ease, »
    color 0.2s linear;
  -moz-transition: background .3s ease, »
    color 0.2s linear;
  -o-transition: background .3s ease, color 0.2s linear;
  transition: background .3s ease, color 0.2s linear;
  }
a.foo:hover,
a.foo:focus {
  color: #030;
  background: #690;
  }