Category Archives: CSS

Technique To Display Product Ratings Using CSS

One of the built-in functions of Magento, or any ecommerce platform for that matter, is the ability for users to submit product ratings and then have those ratings displayed next to each product. This is rendered as a fractional number of stars from 0 to 5. For example:

Example Product Rating

The skin that ships with Magento does this with HTML, CSS, and a background image. In this article, I describe this technique.

This technique uses a background image sprite consisting of both the “active” and “inactive” stars with a transparent background:

Example star rating background sprite

(Click the image to view/download)

Notice that this sprite contains just one star for each state (active vs. inactive). The CSS repeats the top star horizontally for the “inactive” stars in an outer DIV and repeats the bottom star horizontally for the “active” stars in an inner DIV. The magic is using a percentage width for the “active” stars.


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

The CSS:

.rating-box {
background: url("../images/bkg_rating.png") repeat-x;
font-size: 0;
height: 13px;
line-height: 0;
overflow: hidden;
text-indent: -999em;
width: 70px;

.rating-box .rating {
background: url("../images/bkg_rating.png") repeat-x;
background-position: 0 100%;
float: left;
height: 13px;

This combination of HTML, CSS, and PNG will create a 4 out of 5 star rating (i.e., 80%). The server-side code should render the inline style for the inner DIV by computing a percentage based off of the product’s current rating and the total possible and rounding the number to a valid percentage (i.e., an integer value between 0 and 100).

A PHP example:

$rating = round(($prod->getRating() / 5) * 100);
<div class="rating-box">
<div style="width: <?php echo $rating; ?>%" class="rating">

Some things to consider if you want to design your own background sprite or if you want a rating system with a different maximum (e.g., nof 3):

  • The width of the outer DIV should be about n times the width of the graphic, where n is the maximum rating.
  • The height of both the inner and outer DIV elements should be the height of one rating.

That’s it. I think it’s a pretty simple, elegant technique. Try it out and let me know how it goes.