Loading lessons...
Image Sprites
Image Sprites
Combine many small images into ONE image file, then move a "window" over it to show each one. Saves HTTP requests = faster pages!
The technique
- The container has a fixed
widthandheight. background-imagepoints to one combined sprite file.background-positionslides the visible window.
.icon-home {
width: 30px;
height: 30px;
background-image: url("sprite.png");
background-position: 0 0; /* leftmost icon */
}
.icon-cart {
width: 30px;
height: 30px;
background-image: url("sprite.png");
background-position: -30px 0; /* shifted 30px left */
}
.icon-mail {
width: 30px;
height: 30px;
background-image: url("sprite.png");
background-position: -60px 0; /* shifted 60px */
}
Hover state
Swap to a second row of the sprite on hover (common for buttons):
.btn-play {
width: 50px;
height: 50px;
background: url("buttons.png") 0 0 no-repeat;
}
.btn-play:hover {
background-position: 0 -50px; /* second sprite frame */
}
Why use sprites?
- Fewer HTTP requests = faster pages.
- One file caches once for the whole site.
- No flash between hover states.
TL;DR
- Sprite = many images packed into one file.
- Set container w/h, then offset the image background.
background-positionmoves the visible "window".- Use hover to flip frames instantly.