Hover Effect


navigation images
An Image Sprite

The :hover selector can be used on all elements, not only on links. On the left, notice a new image (img_navsprites_hover.gif) which contains three navigation images and three images to use for hover effects. We shall add a hover effect to our navigation list.

Because this is one single image, and not six separate files, there will be no loading delay when a user hovers over the image. We only add three more lines of code to the CSS stylesheet to add the hover effect:

HTML file: Displayed by browser:
<style>
#navlist {
    position: relative;
}
#navlist li {
    margin: 0;
    padding: 0;
    list-style: none;
    position: absolute;
    top: 0;
}
#navlist li, #navlist a {
    height: 44px;
    display: block;
}
#home {
    left: 0px;
    width: 46px;
    background: url(../html_beg/images/img_navsprites_hover.gif) 0 0;
}
#prev {
    left: 63px;
    width: 43px;
    background: url(../html_beg/images/img_navsprites_hover.gif) -47px 0;
}
#next {
    left: 129px;
    width: 43px;
    background: url(../html_beg/images/img_navsprites_hover.gif) -91px 0;
}
#home a:hover {
    background: url(../html_beg/images/img_navsprites_hover.gif) 0 -45px;
}
#prev a:hover {
    background: url(../html_beg/images/img_navsprites_hover.gif) -47px -45px;
}
#next a:hover {
    background: url(../html_beg/images/img_navsprites_hover.gif) -91px -45px;
}
</style>
<body>
<ul id="navlist">
  <li id="home"><a href="demo.html"></a></li>
  <li id="prev"><a href="demo.html"></a></li>
  <li id="next"><a href="demo.html"></a></li>
</ul>
</body>

CSS example explained:

  • #home a:hover {background: transparent url(../html_beg/images/img_navsprites_hover.gif) 0 -45px;}

         - For all three hover images we specify the same background position, only 45px further down

A lot of mental exercise, but with practice, this could be an interesting challenge! It sure makes sense to use image sprites for images that may be used repetitively.

Back button Table of Contents Next button