Search This Blog

Image sprite magic!

posted on Monday, October 22, 2012

Image sprites, I mentioned the topic in one of my last posts: and promised to dedicate an entire post to the matter... behold, an entire post on image sprites!

If you are not (yet) familiar with image sprites, then I can tell you that it's definitely not what you think it is based on the name :) It is actually a pretty cool css technique that speeds up and simplifies the process of switching state images. How? By grouping related images in one file! Confused yet? No worries, one clear explanation coming up!

Normally when you need an image for a button, you'll have a separate image and thus a separate file for each state of that button, so the normal state, the active state and the hover state. Three images so three files as you can see below on the left.

Three images, three separate files
418 bytes
419 bytes
414 bytes
Three images, single file

         960 bytes

The concept of image sprites is that you group this type of related images in one file, as you can see above on the right. Why? Because instead of loading three files, your visitors will only have to load one image which will be reused. That one file will also be smaller than the three separate files combined. On top of that, technically speaking, when you switch between images (on a hover action, for example) this should happen faster because the file is already loaded, it only changes position.

The code below shows how the image is used for the default button state. For each other state the background-position is switched to move the background-image to show the part of the image that you want to use for that state.
    margin: 0;
    padding: 0;
   a#button, a#button:active
    color: #FFF;
    display: block; 
    background: url(all.png) no-repeat top left; 
    padding: 9px 5px;
    color: #000;
    background-position: center left; 
    background-position: bottom left; 
<a alt="Great blog" href="" id="button" target="_blank">This is a button</a>
Unfortunately the Blogger file concept and a lack of personal hosting space makes it impossible for me to post a live example but if you copy and save the code above, you should get the picture :P

That's it! A pretty easy and cool css trick!

Could be useful, right?

No comments:

Post a Comment