CSS image sprites are a technique where a single image file is used to display multiple images on a webpage. This technique can be used to reduce the number of HTTP requests needed to load a page, improving page load times and reducing server load.
To create an image sprite, you can combine multiple images into a single image file using an image editor or other tools. You can then use CSS to display the individual images within the sprite as needed.
Here is an example of using a CSS image sprite to display two different images on a webpage:
HTML code:
<div class="sprite"></div>
CSS code:
.sprite {
width: 50px;
height: 50px;
background-image: url("sprite.png");
background-position: 0 0;
}
.sprite:hover {
background-position: -50px 0;
}
In this example, we have a div with a class of “sprite”. We set the width and height to 50 pixels and specify the sprite image using the background-image property. We then use the background-position property to display the first image within the sprite.
When the user hovers over the div, we use the :hover pseudo-class to display the second image within the sprite by changing the background-position property.
This technique can be used to display any number of images within a single sprite image, and can greatly improve the performance of a webpage by reducing the number of HTTP requests needed to load the page.