Reviews Stars
Posted on | March 11, 2015 | No Comments
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):
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:Richard Parnaby-King