CSS Image Sprites
Image sprites combine multiple images into a single file, reducing the number of HTTP requests. By shifting the background-position property, you can display different parts of the sprite as separate icons or images. Sprites improve performance and can simplify icon management.
Key Topics
- Single Image File
- Background-position for Different Icons
- Performance Optimization
Example
Set background-image
to the sprite file, then adjust background-position
to show the desired icon.
.icon {
width: 32px;
height: 32px;
background-image: url('icons-sprite.png');
display: inline-block;
}
.icon-home {
background-position: 0 0;
}
.icon-search {
background-position: -32px 0;
}
Explanation: The home icon is at (0,0) in the sprite, while the search icon is shifted 32px left to display the appropriate portion of the image.
Key Takeaways
- Efficiency: Fewer image requests speed up page load.
- Organization: All icons in one file, managed through CSS positions.
- Consistency: Ensures all icons share a similar style and dimension.