top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is a sprite? How is it applied using CSS? What is the benefit of it?

0 votes
491 views
What is a sprite? How is it applied using CSS? What is the benefit of it?
posted Jun 28, 2017 by Sisir Jana

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Sprite

Sprites are two-dimensional images which 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.

How to use CSS Sprites

Here's an example sprite, with three different countries flags combined into a single image:

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.

Benefit of CSS Sprites

It may seem counterintuitive to cram smaller images into a larger image. Wouldn't larger images take longer to load?

Let's look at some numbers on an actual example:

enter image description here

That adds up to a total of 14.38KB to load the three images. Putting the three images into a single file weighs in at 16.1KB. The sprite ends up being 1.72KB larger than the three separate images. This isn't a big difference, but there needs to be a good reason to accept this larger file... and there is!

While the total image size (sometimes) goes up with sprites, several images are loaded with a single HTTP request. Browsers limit the number of concurrent requests a site can make and HTTP requests require a bit of handshaking.

Thus, sprites are important for the same reasons that minifying and concatinating CSS and JavaScript are important.

answer Jun 30, 2017 by Biplab Roy
...