I found this flexible, one-image rating widget built with SASS by AirBnB. I’d like to create something similar with LESS. I know I could just write out the CSS, but I’d like to do it dynamically with LESS. My main problem seems to be dynamically adding the counter _1 … _10 to the class (.filled_1 … filled_10). Is this possible in LESS?
Here’s the working SASS code:
$starWidth: 44px;
$starOffset: 0 -43px;
$numStars: 5;
$steps: 2;
$total: $numStars * $steps;
@mixin filled($n: 0) {
width: ($starWidth / $steps) * $n;
}
.stars {
background: url(/images/sprite.png) repeat-x top left;
height: 43px;
&.empty {
background-position: $starOffset;
width: $numStars * $starWidth;
}
@for $i from 0 through ($total) {
&.filled_#{$i} { @include filled($i) }
}
}
This turns out code like this in CSS:
.stars {
background: url(/images/sprite.png) repeat-x top left;
height: 43px; }
.stars.empty {
background-position: 0 -43px;
width: 220px; }
.stars.filled_0 {
width: 0px; }
.stars.filled_1 {
width: 22px; }
.stars.filled_2 {
width: 44px; }
.stars.filled_3 {
width: 66px; }
.stars.filled_4 {
width: 88px; }
.stars.filled_5 {
width: 110px; }
.stars.filled_5 {
width: 132px; }
.stars.filled_7 {
width: 154px; }
.stars.filled_8 {
width: 176px; }
.stars.filled_9 {
width: 198px; }
.stars.filled_10 {
width: 220px; }
How can I do the same loop and include in LESS instead of CSS?
The final HTML will look like this: (where 9 will show 4.5 stars)
<div class="stars empty">
<div class="stars filled_9">4.5</div>
</div>
Stackoverflow user GnrlBzik shared a looping strategy for LESS, but the result looked more complex than I had hoped. Here is a working solution that still looks elegant for those that will have a static amount of stars.