CSS Image Sprites

css image sprites
10 November 2024

Using Image Sprites in CSS is one of the techniques commonly employed in web design to reduce the number of requests to the server and improve the performance of web pages.

In this technique, instead of using multiple separate images, all necessary images are combined into a larger single image file. In this scenario, the web page only needs to make one request to the server to fetch this single image, and through CSS, it displays different portions of the image as needed.

The Image Sprite technique is usually used to display icons and small images that are shown in multiple locations on a page. This way, in addition to reducing the number of requests, due to a single loading of the image, the size of the received data can also be decreased.

As an example, suppose you have a sprite that includes several different icons. Instead of loading each icon separately, you can use one large image that contains all the icons. Then, by using appropriate CSS properties, you can display each icon in its designated location.

In the following, a sample code for implementing CSS Image Sprites is provided:


.icon {
  width: 50px;
  height: 50px;
  background-image: url('sprite.png');
}
.icon-home {
  background-position: 0 0;
}
.icon-profile {
  background-position: -50px 0;
}
.icon-settings {
  background-position: -100px 0;
}

In this example, the class .icon specifies the dimensions and background image.
The class .icon-home refers to the background position of the first image, in this case, the home icon.
The class .icon-profile indicates the position of the image showing the profile icon.
The class .icon-settings is for the settings icon, utilizing the third section of the image.
In this way, multiple icons can be shown in response to one HTTP request.

FAQ

?

How do we work with Image Sprites in CSS?

?

Why should we use Image Sprites?

?

Do Image Sprites affect responsive design?