HTML5, CSS3, and JavaScript Fourth Edition

(Ben Green) #1

CHAPTER 11. HOVER AND PSEUDO CLASSES 124


Here is a solution that uses CSS and transitions to scroll the image from the
visible part to the invisible part. With this approach, you create one larger
image that has each of the smaller images embedded in it. The first three
lines are CSS. The last line is HTML.


One big advantage of this approach is that there is only one image to be
loaded. When two separate images are involved, there can be a delay while
the second image is retrieved from the server.


div#x { background-image: url(1.jpg);
transition: background-position 2s; }
div#x:hover { background-position: -400px 0; }



The scrolling image approach is very powerful but also takes more work in
preparation. It can make a nice slide show.


Cross Fading Images (Animated)


Here is a solution that uses opacity to fade one image out and fade the other
image in. We wrap the first img inside a div, and set the background image
of the div to be the second image. Then when we hover over the image, we
transition the opacity of the first image slowly to zero, revealing the second
image.


Because both images are loaded initially, there is no delay to load the second
image when the user causes the cross fading to begin.


img { transition: opacity 2s; }
img:hover { opacity: 0; }




Thealt=""is needed because img tags are required to have an alt attribute,
whether it is blank or not.


11.7 For Further Study


Google search “pseudo classes” to get lists of options that are available.

Free download pdf