What is Sprites and Why We Want to Use Them?


Sprite basically is one larger image which contains few or many smaller images aligned horizantlly or vertically one image per row or column. What benefit we get from using sprites rather than single images? faster loading times, less HTTP protocols, less traffic. Also in this page I have used some sprites, like small icons for blog toolbar in right side, so instead of using 12 different images (6 blue+6 white) i used only one, so every time anyone opens my blog, he nneed to download only one image for blog icons instead of 12 different images.

sprite for blog icons So my sprite for blog icons looks like this, and insted of displaying images I display div's with background, which is positioned  using background-position atribute.

There is a lot of online tools for creating sprites, my favorite is http://instantsprite.com/ which converts all images to sprite and gives you the HTML and CSS codes.

it uses CSS selectrors for displaying right images, and the code is somethong like this


<div class="blog-icon phone"></div>
<div class="blog-icon blog"></div>

and CSS for displaying right icon for div:

.blog-icon { background: url('/img/theme/blog-icon.png')
no-repeat top left; width: 16px; height: 16px; float: left; margin: 5px 4px 0 0;}
.blog-icon.blog { background-position: 0px 0px; }
.blog-icon.phone { background-position: 0px -104px; }

So what does this? 
It says, that our div will be 16x16 px big, .blog-icon.blog background position will be 0px from left side and 0px from top.
.blog-icon.phone divs background position will be 0px from left side and 104px from top, did you saw the "-"? that is how you set position from top for sprites as div background.

so what we achieved? instead of downloading 12 seperate images we had to downlad just one. this can save us from broken image links on hover efect, or just broken image link. we saved some KB in traffic and we improved loading speed, because of doing 12 HTTP protocols we get image only in one protocol. 


there won't be easy way to edit size, if you decide to have 32x32 icons later, you will have to redo this from zero. starting with creating 32x32 px icons and making sprite from them.