• View our reviews on Hot Scripts
  • JS Tutorial

Recent Comments

Powered by Disqus

Back to articles

Display simple CSS star rating

Rate feature not only provides you with feedback what content do your visitors like, but it is also a motivator for you to provide visitors with more quality content. Usually these ratings are displayed as number or percentage, which doesn't look pretty attractive. But there is an easy and also cool way to display rating using stars.

You probably had seen it before:



And here is a simple method how to do it. We will use this image with two stars: empty and full.

For example we will use rating with maximum 5 starts.

We'll use this css code to fill each div element with it's own star type:

.rating_bar {
    /*this class creats 5 stars bar with empty stars */
    /*each star is 16 px, it means 5 stars will make 80px together */
    width: 80px;
    /*height of empty star*/
    height: 16px;
    /*background image with stars */
    background: url(/images/stars.png);
    /*which will be repeated horizontally */
    background-repeat: repeat-x;
    /* as we are using sprite image, we need to position it to use right star, 
    //0 0 is for empty */
    background-position: 0 0;
    /* align inner div to the left */
    text-align: left;
.rating {
    /* height of full star is the same, we won't specify width here */
    height: 16px;
    /* background image with stars */
    background: url(/images/stars.png);
    /* now we will position background image to use 16px from top, 
    //which means use full stars */
    background-position: 0 -16px;
    /* and repeat them horizontally */
    background-repeat: repeat-x;

Then you need to calculate percentage of your rating, to use this percentage in div width. To calculate percentage of your rating you can use this simple formula: round((rating/max_rating)*100).

For example, if we have maximal possible rating 5, and current rating is 2, then percentage is:

round((2/5)*100) = round(0.4*100) = 40%

And then we'll use this html code with calculated data:

<!-- div element full of empty stars -->
<div class='rating_bar'>
    <!-- div element that contains full stars with percentage width, 
    which represents rating -->
    <div  class='rating' style='width:40%;'>

And here you can try it out yourself, enter values from 0 to 5, like 3.6 for example, and see how it is displayed.




You may also be interested in:

Powered by

blog comments powered by Disqus