Image Sprites in CSS
? Image Sprites in CSS
Image sprites combine multiple images into a single image file. Using CSS, you display only a part of that big image as needed, reducing HTTP requests and improving page load speed.
How Image Sprites Work
A sprite sheet is one large image containing many smaller images (icons, buttons, etc.).
Use
background-image+background-positionto show the correct part.Change
background-positionto switch which sprite is visible.
Basic Example
Sprite Sheet (example)
Imagine a sprite sheet that looks like this (3 icons horizontally):
[icon1][icon2][icon3]Each icon is 32x32 pixels.
HTML
<div class="icon icon-home"></div><div class="icon icon-search"></div><div class="icon icon-settings"></div>CSS
.icon { width: 32px; height: 32px; background-image: url('sprites.png'); background-repeat: no-repeat; display: inline-block;}/* Show the first icon */.icon-home { background-position: 0 0;}/* Show the second icon (shift 32px left) */.icon-search { background-position: -32px 0;}/* Show the third icon (shift 64px left) */.icon-settings { background-position: -64px 0;}Why Use Image Sprites?
Reduces the number of HTTP requests (better performance).
Easy to manage multiple icons/buttons in one file.
Works well with CSS hover states (shift background-position).
Advanced Tips
Combine with CSS
:hoverto change icons on hover.Use tools to automatically generate sprite sheets.
Works great for UI icons, buttons, social media icons.
Example with Hover Effect
.icon-home:hover { background-position: 0 -32px; /* Change sprite on hover */}Want me to help you create a sprite sheet or a working demo with image sprites?