Pro CSS3 Animation

(Tuis.) #1

Chapter 3 ■ CSS3 tranSitionS for imageS


changes to the images will have to be made in different places, as one image will exist solely in CSS and the other
as an HTML element. The second option may involve a little more code, but has the benefit of keeping both
pictures as elements and thus remains more accessible. The third option is technically outside the spec as
of this writing, but has perhaps the greatest ease of use.
I will demonstrate all three methods using photographs supplied by Ton Rulkens
(www.flickr.com/photos/47108884@N07/4595559479/) and Peter Shanks
(www.flickr.com/photos/botheredbybees/1954163161/), used with permission.
Both of the images must be exactly the same size. There are several ways of achieving this:


•    Crop the images to the same dimension in an application such as Adobe PhotoShop (this
is the most obvious solution).

•    You can modify the width and height of the images through CSS or HTML attributes,
although this often leads to visual distortion.

•    You can set a width and height on the div and use overflow:hidden to trim off portions
of the images that fall outside this area.

•    If both images are represented as elements in the code, you can use the same CSS clip
values for each.

Option 1: First Image As a CSS Background


The HTML for this option is very simple, as shown in Listing 3-1.


Listing 3-1. HTML Option 1 to Create Two Layered Images



Jatropha hybrid leaf

■ Note htmL5 code samples shown in this book are in “minified” syntax to save space. elements are closed only

when needed and attribute values are only quoted if they contain spaces.

The CSS shown in Listing 3-2 is also very simple.

Listing 3-2. CSS to Create a Cross-fade Effect for HTML Option 1


div.crossfade { background: url(leaf-veins.jpg); background-size: cover; }
div.crossfade, div.crossfade img { width: 418px; height: 500px; }
div.crossfade img { transition: 3s opacity ease-out; }
div.crossfade img:hover { opacity: 0; }


Option 2: Both Images As HTML Elements


Alternatively, you can stack both images inside a single container as individual pictures; the HTML is shown in
Listing 3-3.

Free download pdf