August 8, 2012

Display Star Ratings Using CSS Sprites

Almost all rating systems you come across use stars to represent the numeric information visually. There are many ways to display the star rating, some involve using six or more images, while others require an image sprite that contain two, six or even more images. However, I like the star ratings used on Google search results page because it uses very simple CSS and sprite; and it can display fractional values (e.g. 3, 3.5, 3.75) quite nicely.

To create something similar, all you need is an image sprite containing two images (gray and yellow stars for example) and some CSS. Here is the 65x26px sprite used in the following example:

Star rating image sprite

The HTML/CSS markup consists of two span tags:

  1. The outer span has gray rating graphic as its background image and its dimensions match those of the graphic.
  2. The inner span has yellow rating graphic as its background image and its width is specified in percent. This means it can display any rating value on the scale; for example, to display a rating of 3.5 out of 5, set the width to 70%.

Here is what it looks like:

<span style="display: block; width: 65px; height: 13px; background: url(star-rating-sprite.png) 0 0;">
    <span style="display: block; width: 70%; height: 13px; background: url(star-rating-sprite.png) 0 -13px;"></span>
</span>

And here is the result:

The sprite image is a truecolor PNG with alpha channel which allows it to blend nicely with any background color:

Rating: 1.0
Rating: 2.5
Rating: 4.0

More examples:

Gradient
Hearts

UPDATE: Note that it is possible to use a more compact image sprite that contains just two stars: one gray, one yellow; you can display less than/more than five stars that way by changing the width of the outer span.