An image sprite consolidates multiple images into a single image file, which helps optimize loading times and reduce server requests for web pages with numerous images, ultimately conserving bandwidth.
Instead of employing three distinct images, we utilize a single image named “img_navsprites.gif”.
Through CSS, we can selectively display only the required portion of the image.
In the forthcoming example, the CSS specifies the segment of the “img_navsprites.gif” image to display.
Example
#home { width: 46px; height: 44px; background: url(img_navsprites.gif) 0 0; } |
Example explained:
This method provides a straightforward approach to utilize image sprites, and now we aim to enhance it by incorporating links and hover effects.
We aim to utilize the sprite image (“img_navsprites.gif”) to construct a navigation list.
Utilizing an HTML list is preferred as it supports both links and background images.
Example
#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(‘img_navsprites.gif’) 0 0; } #prev { left: 63px; width: 43px; background: url(‘img_navsprites.gif’) -47px 0; } #next { left: 129px; width: 43px; background: url(‘img_navsprites.gif’) -91px 0; } |
Example explained:
Let’s now proceed to position and style each specific component accordingly.
Next, we aim to implement a hover effect for our navigation list.
Tip: The :hover selector is applicable to all elements, not just links. |
Our updated image (“img_navsprites_hover.gif”) comprises three navigation images and three images designated for hover effects.
As this is a single image file rather than six distinct files, there will be no loading delay when a user hovers over the image.
We only need to include three lines of code to implement the hover effect.
Example
#home a:hover { background: url(‘img_navsprites_hover.gif’) 0 -45px; } #prev a:hover { background: url(‘img_navsprites_hover.gif’) -47px -45px; } #next a:hover { background: url(‘img_navsprites_hover.gif’) -91px -45px; } |
Example explained: