Image sprites with CSS
15 okt. 2012One method of speeding up loading of a web page is by avoiding unnecessary GET requests. The HTML body usually contains a lot of additional resources like javascript, css and images. Using CSS it is possible to merge images like icons into a single file and show the different parts of the image where appropriate. My motivation for doing this wasn't speed, but the frustration of my console getting filled with one line per icon for every page request when developing with django's development server, and the fact it made it more difficult to find my print statements for variables I wanted to verify. Anyway...
First step: Generate the single image. The CSS Sprite Generator at projectfondue.com is an excellent tool for this job. Archive/zip all your images, upload them and have the grid be generated automatically. In my case I got this image returned together with this code:
.sprite-500px{ background-position: 0 0; width: 38px; height: 38px; }
.sprite-facebook{ background-position: 0 -48px; width: 38px; height: 38px; }
.sprite-feed{ background-position: 0 -96px; width: 38px; height: 38px; }
.sprite-flickr{ background-position: 0 -144px; width: 38px; height: 38px; }
.sprite-github{ background-position: 0 -192px; width: 38px; height: 38px; }
.sprite-google{ background-position: 0 -240px; width: 38px; height: 38px; }
.sprite-linkedin{ background-position: 0 -288px; width: 38px; height: 38px; }
.sprite-spotify{ background-position: 0 -336px; width: 38px; height: 38px; }
.sprite-twitter{ background-position: 0 -384px; width: 38px; height: 38px; }
Next step: Use the images.. Now this was a bit more tricky! My goal was to show each of these social icons as clickable links with some hover effect. The HTML looks like this:
<div class="pull-right">
<ul>
<li class="sprite sprite-feed">
<a target="_blank" href="/rss/"></a></li>
<li class="sprite sprite-spotify">
<a target="_blank" href="/databases/spotify/"></a></li>
<li class="sprite sprite-500px">
<a target="_blank" href="http://500px.com/andynor"></a></li>
..etc...
</ul>
</div>
Don't mind the pull-right class, it's bootstraps way of pulling the div to the right :)
In order to show the images, and make the link clickable for the whole parent <li> item I used the following code
.sprite {
display: block;
float: left;
margin-left: 5px;
background: url(../img/social_icons.png) no-repeat top left;
height: 38px;
width: 38px;
-webkit-filter: grayscale(1) opacity(0.5); /* Google Chrome & Safari 6+ */
}
.sprite a{
position: absolute;
width: 38px;
height: 38px;
}
.sprite:hover{
-webkit-filter: grayscale(0) opacity(1); /* Google Chrome & Safari 6+ */
}