In this tutorial we’ll discuss how we can use CSS to display the stars in a very elegant manner. It even allows to show any rating very clearly, so you’d be able to distinguish a rating of 3.8 from a rating of 4.2!
Using the 5 star rating system
Look at this example: How it works
The stars are constructed out of only two images.
bright star: faint star: The html for these stars is very simple – one DIV inside another:
Code: Select all
<div class="rating_bar">
<div style="width:51%"></div>
</div>
The class on the outer DIV allows us to apply CSS. The CSS used is as follows:
Code: Select all
.rating_bar {
width: 55px;
background: url(/img/star_x_grey.gif) 0 0 repeat-x;
}
.rating_bar div {
height: 12px;
background: url(/img/star_x_orange.gif) 0 0 repeat-x;
}
The second rule-set applies to the inner DIV. The height needs to be the height of your star image. The bright star image is set as the background image.
This all combines to create our example: You can think of it as two layered boxes. The lower one is filled with the faint stars and takes up the entire width. The upper one contains the bright stars and it’s width is what conveys the bar’s meaning. Here is the same thing again, but with coloured borders to reveal the edges of the boxes: Pretty simple, huh!
Extending the system to create rating bars
You could use this system with many kinds of images. Another good image to use is a coloured bar.
Use these bars, to create this one. An advantage of this method over the stars is that the entire bar can be any width. It doesn’t have to be the exact width of five stars or anything.
An even fancier bar
You can add a rounded end to the bar itself: To do this, you need an extra image: …and an extra inner DIV:
Code: Select all
<div class="rating_bar">
<div style="width:52%">
<div></div>
</div>
</div>
Code: Select all
.rating_bar div div {
background: url(/img/rating_bar_tip.gif) right 0 no-repeat;
}
There are a couple of alternatives to this system. You could display one IMG element for each star and calculate how many bright and faint stars you need. This means that you have more HTML (more for your visitors to download). It also restricts you to displaying full or perhaps half-stars.
Another method is to create a whole lot of different images – one for each possible combination of stars. This would result in less HTML, but more images for your visitors to download. And you are restricted to as many permutations as you can be bothered creating.
But I don’t want two-fifths of a star
You may decide that you only want to display whole stars (or half stars). This is easy to accomplish by first rounding the percentage width of the bar. If you only want to display whole stars, then round the percentage to the nearest 20%. This method still has advantages over the alternatives because it results in less HTML.