← Back to Chapters

CSS Image Sprites with Hover Navigation

? CSS Image Sprites with Hover Navigation

⚡ Quick Overview

Image sprites are a performance technique where multiple small images (icons, buttons, states) are combined into a single image file. Instead of downloading many separate images, the browser downloads one sprite sheet and CSS is used to display just the part we need with background-position.

In this navigation example, the sprite image from W3Schools (img_navsprites.gif) contains three icons — home, previous, and next — each with a hover state in the same file.

? Key Concepts

  • All icons come from one file: img_navsprites.gif.
  • Only the background position changes on hover.
  • Each button has a fixed width and height.
  • No JavaScript is required for hover effects.

? Syntax & Theory

The background position changes vertically to reveal the hover version of each icon.

? View Code Example (Sprite CSS)
/* Normal & hover positions from the sprite sheet */
#home a { background-position: 0 0; }
#home a:hover { background-position: 0 -44px; }

#prev a { background-position: -47px 0; }
#prev a:hover { background-position: -47px -44px; }

#next a { background-position: -91px 0; }
#next a:hover { background-position: -91px -44px; }

? Example HTML Markup

? View Code Example (HTML)
<!-- Sprite-based navigation list -->
<ul id="navlist">
  <li id="home"><a href="#" aria-label="Home"></a></li>
  <li id="prev"><a href="#" aria-label="Previous"></a></li>
  <li id="next"><a href="#" aria-label="Next"></a></li>
</ul>

Demo Navigation

Hover each icon below to see the sprite shift vertically.

? Measuring Sprite Positions

  • Open the image in a design tool.
  • Measure each icon block size.
  • Offsets become your background-position.

? Tips

  • Use consistent icon sizes and spacing in your sprite image.
  • Always specify width and height for the elements using sprites.
  • Test your sprite alignment across different browsers and screen DPIs.
  • Compress and optimize the sprite image to reduce file size.
  • Consider separate sprite sheets for light and dark themes if needed.

? Practice Exercises

  1. Create your own sprite image with four social media icons (Facebook, Twitter, LinkedIn, Instagram).
  2. Write CSS using background-position to show each icon in a navigation list.
  3. Add a hover effect by changing the background color or swapping to a different sprite row.
  4. Build a full navigation menu that uses sprites for icons next to text labels.