1.

What is the importance of CSS Sprites?

Answer»

CSS sprites are used for combining multiple images in a single larger image. They are commonly used for representing icons that are used in the user interfaces. The main advantages of using sprites are:

  • It reduces the number of HTTP requests to get data of multiple images as they are acquired only by sending a single request.
  • It helps in downloading assets in advance that help display icons or images upon hover or other pseudo-states.
  • When there are multiple images, the BROWSER makes separate calls to get the image for each of them. Using sprites, the images are combined in one and we can just call for that image using one call.

Consider an example where our APPLICATION requires 3 images as shown below (Without Sprites Section). If we are trying to load the images independently, we require 3 different HTTP Requests to get the data. But if we have CSS Sprites where all 3 images are combines into 1 separated by some spaces, then we require only 1 HTTP Request.

We can access each image from the sprite by accessing the positioning properties as shown in the below code:

<!DOCTYPE html><html><head><style>#home-icon { left: 0px; width: 46px; background: url('spriteFile.gif') 0 0;}#prev-icon { left: 63px; width: 43px; background: url('spriteFile.gif') -47px 0;}#next-icon { left: 129px; width: 43px; background: url('spriteFile.gif') -91px 0;}</style></head><body><img id="home-icon" src="spriteFile.gif" width="1" height="1"> <!-- To display home icon here --><img id="next-icon" src="spriteFile.gif" width="1" height="1"> <!-- To display next icon icon here --><img id="prev-icon" src="spriteFile.gif" width="1" height="1"> <!-- To display PREVIOUS icon icon here --></body></html>

In the above code, we are trying to access each element - house, previous and next icon - from the sprite file by using the left, width properties. The image is displayed in the img section by means of the background property. Do note that the source of the image (src attribute of the img tag) is just one file which is the spriteFile.gif and depending on the rules SPECIFIED in the id selectors, the images are loaded ACCORDINGLY.



Discussion

No Comment Found