cott Cheng

CSS Multi-Transition Trick

It’s one thing to know a tool, another to make the most of it.

Transition is one of my favorite features that CSS3 has brought to the front-end toolkit. Smooth color change on hover can be achieved as easily as the following (see links on this site for live examples):

Smooth hover color change (anchor)
1
2
3
4
5
6
7
a {
  color: #555;
  transiton: color .25s;  /* vendor prefix emitted */
}
a:hover {
  color: #ed6812;
}

This is how I’ve always learned to use the transition property – only apply one transition rule to the element. However, what if we declare another different transition property in the :hover block?

Turns out it does magic. Try moving your mouse in and out of the bar:

Gentle-growing & rapid-dropping
1
2
3
4
5
6
7
8
9
10
11
12
13
#bar-inner {
  width: 5%;

  /* transition rule when not hovered */
  transition: width .5s .5s ease-in;
}

#bar:hover > #bar-inner {
  width: 100%;

  /* transition rule when hovered */
  transition: width 10s 0 ease-out;
}

Here I defined different transition properties on the different “states” (hover and non-hover) of the same element, and made the bar move much slower when hovered (growing) than otherwise (dropping). Also, different delays and timing functions are applied to the different states.

I also used this multi-transition trick to create the trailing dots effect of this experiment, where the dots fade in fast and fade out slowly.

It’s just exhilarating to explore new power of familiar tools.

Comments