CSS Image Sprites
CSS Image Sprites
An image sprite is a single image file that contains multiple smaller images (usually icons). Instead of loading many separate images, the browser loads one sprite and CSS shows the needed part using background-position.
Sprites can improve performance by reducing the number of HTTP requests, especially for icon-heavy interfaces.
How Sprites Work
The idea is simple:
- Create one image that contains multiple icons
- Use
background-imageto set the sprite as the background - Use
background-positionto “move” the sprite so the correct icon appears - Set a fixed width/height so only one icon area is visible
Basic Sprite Example
Assume you have a sprite image named icons.png that contains 3 icons, each 32×32 pixels, placed side-by-side:
/* icons.png layout (example) [ home ][ search ][ user ] 0px 32px 64px */
Create a base class that sets the sprite image and icon size:
.icon {
display: inline-block;
width: 32px;
height: 32px;
background-image: url("icons.png");
background-repeat: no-repeat;
}
Then define classes for each icon using background-position:
.icon-home {
background-position: 0 0;
}
.icon-search {
background-position: -32px 0;
}
.icon-user {
background-position: -64px 0;
}
Usage in HTML:
<span class="icon icon-home"></span> <span class="icon icon-search"></span> <span class="icon icon-user"></span>
Sprite Tips
- Keep a consistent icon size (e.g., 16×16, 24×24, 32×32)
- Use negative
background-positionvalues to shift the sprite - Set
background-repeat: no-repeatto avoid tiling - If your sprite is high-resolution (2x), use
background-sizeto scale it
High-Resolution (2x) Sprite
If you use a sprite that is 2x (for sharpness on high-DPI screens), scale it down using background-size.
.icon {
width: 32px;
height: 32px;
background-image: url("icons@2x.png");
background-repeat: no-repeat;
background-size: 96px 32px; /* total sprite size scaled to 1x */
}
Offsets remain based on the 1x layout.
Code Challenge
Goal: Use a sprite image to display different icons.
HTML:
<div class="toolbar"> <span class="icon icon-home"></span> <span class="icon icon-search"></span> <span class="icon icon-user"></span> </div>
Task:
- Set the sprite image as the background
- Show the correct part of the sprite using
background-position - Add spacing between icons
Try a Solution:
.toolbar {
display: flex;
gap: 10px;
padding: 10px 12px;
border: 1px solid #eee;
border-radius: 12px;
width: fit-content;
}
.icon {
display: inline-block;
width: 32px;
height: 32px;
background-image: url("icons.png");
background-repeat: no-repeat;
}
.icon-home { background-position: 0 0; }
.icon-search { background-position: -32px 0; }
.icon-user { background-position: -64px 0; }
What’s Next?
Next, you will learn how attribute selectors can target elements based on their HTML attributes.