iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Image Sprites

A sprite is a single image containing many smaller icons. CSS background-position picks the right one. Saves HTTP requests in the days before HTTP/2.

Image sprites in practice

EXAMPLE
/* Old-school CSS sprite */
.icon {
  display: inline-block;
  width: 24px;
  height: 24px;
  background-image: url('/icons.png');   /* contains 6 icons */
  background-repeat: no-repeat;
}

.icon-home   { background-position:    0   0 ; }
.icon-search { background-position: -24px   0 ; }
.icon-user   { background-position: -48px   0 ; }
.icon-cog    { background-position:    0 -24px; }
.icon-bell   { background-position: -24px -24px; }
.icon-mail   { background-position: -48px -24px; }


/* In 2026 we usually prefer SVG sprites or icon fonts */

/* SVG sprite - one file, <use> picks an icon */
<svg style='display: none;'>
  <symbol id='icon-home' viewBox='0 0 24 24'>
    <path d='M3 12 L12 3 L21 12 V21 H14 V15 H10 V21 H3 Z' />
  </symbol>
  <symbol id='icon-search' viewBox='0 0 24 24'>
    <circle cx='11' cy='11' r='8' fill='none' stroke='currentColor' stroke-width='2' />
    <line x1='17' y1='17' x2='21' y2='21' stroke='currentColor' stroke-width='2' />
  </symbol>
</svg>

<button><svg width='24' height='24'><use href='#icon-home' /></svg> Home</button>
<button><svg width='24' height='24'><use href='#icon-search' /></svg> Search</button>


/* CSS for SVG icons */
svg { fill: currentColor; }   /* inherits text colour - free theming */
button:hover svg { color: #2563eb; }


/* When CSS sprites still make sense */
/* - Decorative background patterns from a tileset */
/* - Game UI with many small images */
/* - Legacy browsers that struggle with many SVGs */

/* When NOT to use them */
/* - Modern icon libraries (Lucide, Heroicons) are tree-shakable SVG components */
/* - HTTP/2 + Brotli mean many small files are cheap */

Why it matters

CSS sprites were a performance trick for HTTP/1.1. In 2026 use SVG sprites with or import individual SVG components - they are smaller, accessible, and inherit currentColor for free theming. Reach for image sprites only when working with pixel art or legacy systems.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Image Sprites</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Reveal the search icon at -24px from the sprite.

.icon-search { background-image: url('sprites.png'); background- : -24px 0; }

Test yourself

Q1. A CSS sprite combines many icons into…
Q2. How do you show a single icon from a sprite?
Q3. On HTTP/2, sprites matter…

Discussion

Loading…