HTML and CSS Reference
In-Depth Information
As you can see from the CSS, in the hover state the background image is slid 17 pixels to the
left, thus revealing the different portion of the image.
Because the image has already been downloaded for the default state, there is no need to
call a new image off the server, so we have effectively preloaded all the images we need.
Remote Image Swaps
Perhaps you're thinking. “Ah, that's all well and good if I want the image underneath the mouse
pointer to change on hover, but my JavaScript changes an image
elsewhere
on the page. CSS
can't do that, can it?”
Actually, it can . . . but not in all cases. Let's look at an example. The following CSS works
by placing an empty
span
element inside the link that triggers the hover effect, and applying
a unique
id
to that link:
<ul>
<li><a href="nowhere.html"
id="ex4"
>Link one
<span></span>
</a></li>
<li><a href="nowhere.html"
id="ex5"
>Link two
<span></span>
</a></li>
<li><a href="nowhere.html"
id="ex6"
>Link three
<span></span>
</a></li>
</ul>
When the mouse hovers on that link, we can set the
span
element to display as a block-
level element somewhere else on the page (using absolute positioning) and with whatever
background image we want. Because that
span
element is empty, we'll also need to specify
height
and
width
, as illustrated in Figure 8-18; otherwise, it won't show up on the page.
Figure 8-18.
An empty span, positioned absolutely and set to display as a block-level element
and given a fixed height and width (border shown for demonstration purposes only)
And here's the CSS that achieves the aims stated in the preceding section—the positioning
aspects are highlighted in bold:
#ex4:hover span {
background: url(metro.jpg);
background-repeat: no-repeat;
display:block;
width:100px;
height:100px;
position:absolute;
top:450px;
left:300px;
}
#ex5:hover span {
background-image: url(tower.jpg);