user11533661
user11533661

Reputation:

How to color parts of character in HTML?

On my website, I'm using a user rating with five stars. So each user can choose from one to five stars.

And I would like to show the average user rating, with partial colored stars. For example: The average rating is 3.5 stars, three stars should be colored completely, and the fourth star should be colored with 50% horizontal.

I'm using the Font Awesome for showing the stars. So each star is a character, not an image.

3.5 Stars

Is there a solution for this, without using an image? Maybe with CSS?

Until now, I know only solutions to color complete characters with style="color: yellow;", but I would like to color 50% of the fourth character...

Upvotes: 1

Views: 569

Answers (1)

Lee Wise
Lee Wise

Reputation: 900

You could achieve this by having 2 instances of 5 stars, 1 set is yellow stars and 1 is gray. Position the yellow one on top then set the width to a percentage and hide the overflow

.rating {
  display: inline-block;
  position: relative;
  line-height: 1em;
 }
 
 .rating__overlay {
  color: yellow;
  position: absolute;
  top: 0;
  left: 0;
  width: 70%;
  white-space: nowrap;
  overflow: hidden;
}

.rating__base {
  color: #ccc;
  white-space: nowrap;
}
 
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="rating">
  <div class="rating__overlay">
    <i class="fas fa-star"></i>
    <i class="fas fa-star"></i>
    <i class="fas fa-star"></i>
    <i class="fas fa-star"></i>
    <i class="fas fa-star"></i>
  </div>
  <div class="rating__base">
    <i class="fas fa-star"></i>
    <i class="fas fa-star"></i>
    <i class="fas fa-star"></i>
    <i class="fas fa-star"></i>
    <i class="fas fa-star"></i>
  </div>
</div>

Upvotes: 1

Related Questions