Chapter 3 ■ CSS3 tranSitionS for imageS
Listing 3-3. HTML Option 2 to Create Layered Images
Rather than potentially complicating your HTML by attaching a class to the second image, you will use an
nth-child pseudo-selector to alter it, as shown in Listing 3-4.
Listing 3-4. CSS to Create a Cross-fade Effect for HTML Option 2
div.crossfade { position: relative; }
div.crossfade, div.crossfade img { width: 418px; height: 500px; }
div.crossfade img:nth-child(2) { position:absolute; left:0; top:0; transition:
3s opacity ease-out; }
div.crossfade img:nth-child(2):hover { opacity: 0; }
Option 3: Both Images As Backgrounds
While the easiest to code, this option is also the most daring: it is outside the current specification (and, as of this
writing, only supported in Chrome). In this case, the containing div is utterly devoid of content, and everything is
achieved via CSS, as shown in Listing 3-5.
Listing 3-5. CSS to Create an Image Cross-fade Effect (Option 3)
div.crossfade { width: 418px; height: 500px; transition: 3s background-image ease-out;
background-image: url(leaf-veins.jpg); }
div.crossfade:hover { background-image: url(jatropha.jpg); }
If you were willing to push your code even further, an alternative approach would be to use the same empty
div with the CSS4 cross-fade property, shown in Listing 3-6.
Listing 3-6. CSS4 Cross-fade Used to Create an Image Transition
div.crossfade { width: 418px; height: 500px;
background-image: -webkit-cross-fade(url(jatropha.jpg), url(leaf-veins.jpg),0);
transition: 2s background-image linear; }
div.crossfade:hover { background-image: -webkit-cross-fade(url(jatropha.jpg),
url(leaf-veins.jpg),100); }
As its name implies, cross-fade is a more efficient approach, but with limited practical application at this
time; rather than faking a dissolve effect by transitioning opacity, cross-fade processes the images with the
appropriate algorithm.