CSS Image Sprites — Part 2

Posted by on Apr 18, 2011 in Techniques | No Comments

Adding CSS code to style image sprites

This is a continuation of my last post, CSS Image Sprites — Part 1. For my social media buttons, I used one image to create an “image sprite”, which is used make links to Facebook, Twitter and LinkedIn.

In order for this one image sprite to create the effect of three separate social media links with “active” and “hover” states, CSS styling needs to be added for each button. In this example, my image sprite will be divided up into six equal sections, each representing the correct position for the various button states. These positions are broken into either “top” or “bottom” and then “left”, “center” or “right”. Exact positioning may also be used as well.

This is a simple example of using an image sprite to create three buttons with “active” and “hover” states. In the latest site I am working on, a similar technique was used on the navigation bar to create six main buttons that use a “active”, “hover” and “current” state. Using this technique to create website links will help the page load faster because it uses fewer images.

Here’s the CSS code that I used to style the Facebook, Twitter and LinkedIn buttons:

#facebook {display: block; float: left;
height: 42px; width: 35px;
background-image: url(images/social_sprite.jpg); /*All three social buttons use the same image*/
background-position: left top;} /*This positions the image to the left top*/

#twitter {display: block; float: left;
height: 42px; width: 35px;
background-image: url(images/social_sprite.jpg);
background-position: center top;} /*This positions the image to the center top*/

#linkedin {display: block; float: left;
height: 42px; width:34px;
background-image: url(images/social_sprite.jpg);
background-position: right top;} /*This positions the image to the right top*/

a#facebook:hover {background-position: left bottom;} /*This moves the image position to the left bottom*/

a#twitter:hover {background-position: center bottom;} /*This moves the image position to the center bottom*/

a#linkedin:hover {background-position: right bottom;} /*This moves the image position to the right bottom*/

Here are a few sites that give more information on using image sprites:
CSS Image Sprites — a more complete explanation on using CSS to style image sprites
CSS Sprites: What They Are, Why They’re Cool, and How To Use Them

Tags:,

Leave a Reply