Richard Parnaby-King

Web Developer – PHP, Zend Framework and Actionscript 3

Posted on | | No Comments

css-code When viewing a product we all like to see what other people have said about it, so our first stop is to look at the overall customer rating for this product. This is usually in the form of empty/full/partially filled stars out of five.

Review Example

This blog post will teach you how to create a stars-rating using very little HTML and CSS.

The approach is fairly straight forward. We create two divs – the outter div will contain the empty stars, and the inner div will contain the filled stars:

<div class="ratings">
    <div class="rating" style="width:80%"></div>
</div>

But wait, what’s that “width:80%” doing in there? Inline styling is a bad thing! Well, generally yes. However this alters how many full stars are shown. Change the width and watch the rating change :) Obviously you would replace the 80% with the actual rating for this product. In PHP, for example, you would replace the style attribute with:

style="width:<?php echo ($rating/5)*100 ?>%"

We divide the rating by 5 as we are going to show it between five stars. If your rating system was out of ten, you would divide by 10. And so on. The purpose of this is to only show the filled-in stars to the amount specified by the rating.

.ratings {
    background:url(/rating-stars.png) repeat-x scroll 0 0 transparent;
    width:6.8452em;
    height:1.466em;
    display: inline-block;
    position: relative;
    background-size:1.4em;
}
.ratings .rating {
    background:url(/rating-stars.png) repeat-x scroll 0 -1.4em transparent;
    background-size:1.4em;
    height:1.466em;
}

And here’s the stars image I’m using (a single sprite image to keep http requests down):
Rating Stars

And here is the final result:

Conclusion

Two divs, one sprite, and a sprinkle of CSS gives us a very nice little way of showing a precise representation of a product rating.

Do you know of a better approach? Leave a comment.

Posted By:

Comments

  • ABOUT

    Having fifteen years of programming experience in PHP, Zend Framework and ActionScript3, I have a very strong working knowledge of object orientated programming.

    I am a PC Gamer! Playing FPS, RTS, RPG and the occasional MMO since 1996 I have a huge number of a variety of fast-paced games.

  • Recent Posts

  • Categories

  • RSS SUBSCRIBE TO OUR FEED