14.6 Creating Transitions with CSS
In the examples with mouse hovering and using transform, the transition of the effects was a bit messy after all. For example, in /examples/chapter014/14_5_5/index.html, which is shown in Figure 14.55, if you place the mouse cursor over the image, the graphic gets immediately scaled up and rotated, just like a light switch, and then immediately returned to its normal position when you move the mouse somewhere else. If you find this transition a bit too abrupt, you can soften it using the CSS feature transition. This doesn’t require much effort at all, as shown in the following CSS snippet:
...
img {
max-height: 100%;
min-width: 100%;
object-fit: cover;
vertical-align: bottom;
transition: all 1s ease;
}
img:hover {
transform: scale(1.25) rotate(10deg);
border: 4px white solid;
transition: all 1s ease;
}
Listing 14.37 /examples/chapter014/14_6/css/style.css
This example corresponds to the one in Figure 14.55, except that the image gets rotated and enlarged slowly (here exactly within 1 second) while you hover the mouse cursor over it. To ensure that the image gets moved back to the normal position just as slowly and not abruptly, the normal position was also defined using the same transition statement. More actions weren’t necessary so that now there’s no longer a jerky effect in conjunction with transform when you hover over the image. The best thing to do is to try out this example for yourself.
When looking at the transition feature, you’ll notice that three values have been used here: all, 1s, and ease. Strictly speaking, transition is a short notation of the following features:
-
transition-property
Allows you to specify the property to be animated during the transition. With all, you can specify that all properties are animated. You can also specify only individual properties here, such as background for animating. -
transition-duration
This specifies the duration of the transition in seconds. You can also determine the fraction of a second with, for example, 0.2s, which is two tenths of a second. -
transition-timing-function
This specification is a kind of temporal course of the transition. For example, the ease specification used here means that the transition starts slowly, speeds up a bit in the middle, and ends slowly again. There are several such temporal progressions such as linear, ease-in, ease-out, or ease-in-out, which you can try for yourself.
Optionally, you could use transition-delay, which adds a delay at the start of the transition. Consequently, you could alternatively write the short notation of transition used previously as follows:
...
img:hover {
...
transition-property: all;
transition-duration: 1s;
transition-timing-function: ease;
}
...
Examples and Overview of “transition”
For some great demonstrations and examples of transitions using transition, you can visit http://css3.bradshawenterprises.com/transitions/.