This time we are going to talk about a technique that, although it is not very new, is quite useful when it comes to reducing the number of requests and the loading time of our web page; CSS SPRITES.
A sprite is defined as a set of different images grouped together in one image. An example of this would be:
As it is possible to observe, in the image shown we have 3 icons, taking as a premise that to load an image on the web page the time used is 0.2 seconds, if the 3 icons were loaded separately the loading time of the web would increase 3 times that value. That is why css sprites are so useful.
To create a sprite you can use a design program like as Gimp or Photoshop, or simply use an online tool, there are several that provide this service. Once the Sprite has been generated, the way to use it on our website would be as follows:
1.Create the CSS class, which refers to the image that constitutes our sprite. In the same one, using the position attributes, we will indicate which element to show. In addition we can also define the width and height of the same one.
.icn-web{ width:50px; height:40px; background: url(../img/services-icons.png) 0 0 no-repeat; }
2. Make use of our class just in the place where we want to show the icon.
<div class="services-group"> <i class="icn-web"></i> <h4>Servicios Web</h4> </div>
An efficient way to define all the icons, without the need to repeat CSS code for each one would be like this:
1. We define a global class using the selector *, where we indicate that all the elements that begin with our selected prefix have our sprite as background. In this way, we can define other styles that we want to add such as margins or paddings, and assuming that all icons have the same size, we can also define width and height for example:
[class*="icn-"]{ width:50px; height:40px; margin-top: 10px; background: url(../img/services-icons.png) no-repeat; }
2. Then, classes that have the previous prefix are defined, where in each one the position of the icon to be displayed is indicated.
.icn-web{ background-position: 0 0; } .icn-app{ background-position: -50px 0; } .icn-design{ background-position: -100px 0; }
And that’s it, from now on when using several custom icons on a website, it is possible to include them in a single image, using sprites.