A simple CSS/jQuery solution to create fractional star ratings with very little code.
A Pen by Stan Williams on CodePen.
A simple CSS/jQuery solution to create fractional star ratings with very little code.
A Pen by Stan Williams on CodePen.
<div class="container"> | |
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/747/star.svg" class="top-star" /> | |
<h1>Fractional Stars</h1> | |
<h2>Background</h2> | |
<p>I was working on a Drupal based site where we had a number of product nodes that each had a star rating. The client didn't want us rounding the stars off. They wanted 4.7 stars to display as exactly 4.7 stars.</p> | |
<p>I obviously didn't want to write a class for each tenth of each star. Even with Angular and/or Sass helping me, that would have been a giant mess of code.</p> | |
<p>Our Angular setup had a variable that would return the exact number for each node. So all I needed to do was use a touch of jQuery to convert that number into the stars.</p> | |
<p>All you need to make this work is to set the width of a single star in your JS and to wrap your actual rating inside of a span.</p> | |
<h2>Examples</h2> | |
<h3>A 4.7 rating</h3> | |
<p><code><p><span class="stars">4.7</span></p></code></p> | |
<p><span class="stars">4.7</span></p> | |
<h3>A 4.32 rating</h3> | |
<p><code><p><span class="stars">4.32</span></p></code></p> | |
<p><span class="stars">4.32</span></p> | |
<h3>A 3.4 rating</h3> | |
<p><code><p><span class="stars">3.4</span></p></code></p> | |
<p><span class="stars">3.4</span></p> | |
</div> |
// Set this to the width of one star. | |
var starWidth = 40; | |
$.fn.stars = function() { | |
return $(this).each(function() { | |
$(this).html($('<span />').width(Math.max(0, (Math.min(5, parseFloat($(this).html())))) * starWidth)); | |
}); | |
} | |
$(document).ready(function() { | |
$('span.stars').stars(); | |
}); |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> |
.container { | |
width: 400px; | |
background: #449DF5; | |
margin: 0 auto; | |
padding: 40px; | |
color: white; | |
font-family: "Open Sans"; | |
} | |
.top-star { | |
width: 100px; | |
height: 100px; | |
margin: 0 auto; | |
display: block; | |
} | |
h1 { | |
text-align: center; | |
} | |
h2 { | |
margin-top: 35px; | |
} | |
h1, h2, h3, p { | |
margin-bottom: 0; | |
} | |
span.stars, span.stars span { | |
display: block; | |
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/747/star-o-white.svg) 0 0 repeat-x; | |
width: 200px; /* width of a star multiplied by 5 */ | |
height: 40px; /* the height of the star */ | |
background-size: 40px 40px; | |
} | |
span.stars span { | |
background-position: 0 0; | |
background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/747/star.svg); | |
} |