What is a Sprite
Sprite are two-dimensional images that are made up of combining small images into one larger image at defined X and Y coordinates.
To display a single image from the combined image, you could use the CSS background-position property, defining the exact position of the image to be displayed. CSS Sprites is pretty much the exact same theory: get the image once, and shift it around, and only display parts of it. This reduces the overhead of having to fetch multiple images.
Why use CSS Sprites?
It may seem counterintuitive to cram smaller images into a larger image. Wouldn’t larger images take longer to load?
How do you use CSS Sprites?
Here’s an example sprite, with three different countries flags combined into a single image:
You set the same background-image on several CSS classes and set the background position and dimensions of the individual classes to display a single portion of the sprite. Here’s some code that demonstrates the concept:
.flags-canada, .flags-mexico, .flags-usa {
background-image: url('../images/flags.png');
background-repeat: no-repeat;
}
.flags-canada {
height: 128px;
background-position: -5px -5px;
}
.flags-usa {
height: 135px;
background-position: -5px -143px;
}
.flags-mexico {
height: 147px;
background-position: -5px -288px;
}
If you’re thinking that there has to be a way to automate this so that you aren’t manually creating these sprites and then adjusting your stylesheet to match, you’re right, and you’re in luck!
Advantage of Using CSS Image Sprite
A web page with many images, particularly many small images, such as icons, buttons, etc. can take a long time to load and generates multiple server requests.
Using the image sprites instead of separate images will significantly reduce the number of HTTP requests a browser makes to the server, which can be very effective for improving the loading time of web pages and overall site performance.
Get certification for your knowledge in the fundamentals of Computer functioning by clearing the Computer Certification Exam conducted by StudySection. After going through this Computer Certification exam, you will be able to evaluate your basic knowledge of computers.