Divya Manian

RSS Feed Youtube Channel Github

Creating Rating Sprites

I came across this Youtube HTML 5 demo via Laura Carlson and was amazed at their simple sprite solution for static ratings display. Here is how to create one.

Caveat

This solution is only for displaying a static rating and not an animated one.

I am using the word “star” a bit loosely in this post. The “star” in the sprite below is a circle for the sake of simplicity.

Image

Create a sprite as shown below. I have created each circle within an imaginary 20px box so that it is easier to style via CSS. You can use my reference Photoshop file where I have used guides to position each circle at intervals of 20px.

stars sprite

HTML

Put this HTML where you want your ratings to appear:

<span class="rating r0">0/5</span>

The class rating will be used to apply all the common style properties. Classes r0 to r5 will be used to position the sprite as a background image appropriately.

CSS

In your CSS file, add the following:

span.rating {
  background:url("star.png") top left;  
  display:inline-block;
  width:100px; /* width of the set of 5 stars */
  overflow:hidden;
  text-indent:-1000em;  
}                                     

Creating the rating

Now we style each of the r0 to r5 classes.

span.r0 {
  background:-50px 0;
}
span.r1 {             
   background-position:-60px 0; /* assuming each star is 20px wide */      
}      

and so on…

If you use SASS you can add this to your SASS file:
// 100 is the width of the set of 5 stars and 20 is the width of each 
// star (including the space to the right, see the Photoshop file

@for !i from 0 through 5
  span.r#{!i}
    background-position = "#{-(100 - (20*!i))}px 0" 

Here is the demo of the star ratings sprite.

Advantages

  • Single image, lesser page requests, faster page load.
  • Small file size
  • Easier maintainance: You only need to edit one image file in case you want to change the graphic.

Comments