Rating stars with CSS works fine on desktop but not on mobile

Issue

Found a CSS solution for showing rating with stars and all works fine on desktop but on mobile (both ios an andriod) the half star is a bit off.

In Dev Tools on computer it looks fine when emulating phone.

Example of what I mean

.star {
    font-family: Arial;
    font-size: 2em;
    color: gray;
}
    .star:before {
        content: '\2605';
    }
    .star.on {
        color: gold;
    }
    .star.onpercent:after {
        content: '\2605';
        color: gold;
        position: absolute;
        margin-left: -0.832em;
        overflow: hidden;
    }
    .star.onpercent.percent50:after {
        width: 0.42em;
    }
<div class="stars product-container-review-rate-stars" style="position: fixed;">
<span class="star on"></span>
<span class="star on"></span>
<span class="star on"></span>
<span class="star onpercent percent50"></span>
<span class="star"></span>
</div>

Solution

Relying on being able to shift a character by a percentage of a character is not very safe as you have found. It may not just be the mobile devices that give a problem, but different fonts and the way they treat font-size.

A safer way is to use the percentage you want to show as gold as a straight percentage. You can do that by having a linear gradient background image to the star and filling the star with transparent.

This snippet shows that for the 50% case.

.star {
  font-family: Arial;
  font-size: 2em;
  color: gray;
  position: relative;
}

.star::before {
  content: '\2605';
}

.star.on {
  color: gold;
}

.star.onpercent::after {
  content: '\2605';
  color: gold;
  position: absolute;
  left: 0;
  overflow: hidden;
}

.star.onpercent.percent50::after {
  background-image: linear-gradient(to right, gold 0 50%, transparent 50% 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  text-fill-color: transparent;
}
<div class="stars product-container-review-rate-stars" style="position: fixed;">
  <span class="star on"></span>
  <span class="star on"></span>
  <span class="star on"></span>
  <span class="star onpercent percent50"></span>
  <span class="star"></span>
</div>

The nice thing about this method is that it is generalisable. Suppose instead of 50% we used a CSS variable then this could be set by for example JavaScript.

Answered By – A Haworth

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published