Introduction
You don't need more than one image to have 0-5 star ratings.
All you need is a single image containing two different states, some CSS, and the same logic you would use to setup the multi-image based ratings on the backend.
Rating Image
I've attached an image with some simple stars in two states which will accommodate 0-5 stars. The dimensions of the rating block will be 100x20 which works out to 20px by 20px stars and makes the image 200x20.
CSS Classes
Now since ratings are generally something that will be used numerous times on the same page, we want to use classes for our CSS selectors. Below I have a base "star" class with the common attributes of each rating and 5 sub-classes which give me a total of 6 different ratings. (0-5)
It simply shifts the background-position of the image to the left which puts one of the off-state stars out of view on the left and brings one of the on-state stars into view on the right.
.stars, .stars0
{
background: transparent url("stars.png") no-repeat top left;
width:100px;
height:20px;
float:left;
display:block;
margin: 5px;
}
.stars1 {background-position:-20px;}
.stars2 {background-position:-40px;}
.stars3 {background-position:-60px;}
.stars4 {background-position:-80px;}
.stars5 {background-position:-100px;}
With it setup like that all I need to have the backend do is output a number into the HTML using PHP/ASP/CFML/etc for however many stars are needed.
HTML Element
Here are examples of what each stars HTML looks like when it's being used.
<div class="stars stars0"></div>
<div class="stars stars1"></div>
<div class="stars stars2"></div>
<div class="stars stars3"></div>
<div class="stars stars4"></div>
<div class="stars stars5"></div>
I could get away with not using a stars0 class and just using the base stars class when there are no stars for the rating, but having that zero class simplifies the backend operation so that it just has to output a number.
<div class="stars stars<?php echo round($rating); ?>"></div>
Conclusion
There you have it. 5 stars, one image. A little more CSS needed than your usual <img> based solution, but one-fifth of the images and possible connections to the server and HTML that really isn't any more complicated.
This page was published on It was last revised on