CSS Image Sprites
An image sprite packs several small images into one file, then uses background-position to display only the piece you need.
In the past, each icon on a page was its own file, and every file meant a separate network request. A sprite combines them into a single image so the browser downloads one file and shows different regions of it in different places.
How a Sprite Works
You set the combined image as a background, size the element to match one icon, and shift the background with <background-position> so the right icon lines up inside the box. Everything outside the box is clipped away.
Showing one icon from a sprite
<!DOCTYPE html>
<html>
<head>
<style>
.icon {
width: 32px;
height: 32px;
background-image: url('icons.png');
background-repeat: no-repeat;
display: inline-block;
}
.icon-home {
background-position: 0 0;
}
.icon-search {
background-position: -32px 0;
}
.icon-user {
background-position: -64px 0;
}
</style>
</head>
<body>
<span class="icon icon-home"></span>
<span class="icon icon-search"></span>
<span class="icon icon-user"></span>
</body>
</html>Note: Background positions are usually negative because you are pushing the large image up and to the left, revealing the region you want in the top-left of the box.
Why Use Sprites
- Fewer network requests, which historically sped up page loads
- All related icons live in one file that is easy to cache
- Switching icons on hover is instant because the image is already loaded
Changing the Icon on Hover
Hover swap using a second row
<!DOCTYPE html>
<html>
<head>
<style>
.icon {
width: 32px;
height: 32px;
background-image: url('icons.png');
background-repeat: no-repeat;
display: inline-block;
}
.icon-home {
background-position: 0 0;
}
.icon-home:hover {
background-position: 0 -32px;
}
</style>
</head>
<body>
<span class="icon icon-home"></span>
</body>
</html>Note: On modern sites, SVG icons or an icon font often replace bitmap sprites. HTTP/2 also reduced the request cost that made sprites popular, so weigh the maintenance effort before reaching for them.
Exercise: CSS Image Sprites
What is the main performance reason for combining multiple small images into one CSS sprite?