CSS animate star rating one by one

I have the following HTML:

<div class="rating">
  <div class="star active"></div>
  <div class="star active"></div>
  <div class="star active"></div>
  <div class="star"></div>
  <div class="star"></div>
</div>

Output:

★★★☆☆

How do I animate in CSS the active stars, one by one?

I tried:

.star {
   transition: background-color 0.5s ease;
   background-color: #eee;
}

.star.active { 
   background-color: #000;
}

This transitions the color of all the active stars at once. How to I transition the active stars one by one, from left to right?

I am trying to achieve this without JS. The rating score can be anything. Also the range can be any number (there could be 3 or 5 or 8 or 10 stars, etc)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Because of the active class is already assigned, it’s better to use animation instead of transition.

.star {
  background-color: #eee;
}

.star.active {
  animation: star-pop 0.5s ease forwards;
}

@keyframes star-pop {
   to {
      background-color: #000;
   }
}

Then you can give a different animation-delay for different nth-child:

.star.active:nth-child(1) { 
   animation-delay: 0s;
}

.star.active:nth-child(2) { 
   animation-delay: 0.5s;
}

.star.active:nth-child(3) { 
   animation-delay: 1s;
}

.star.active:nth-child(4) { 
   animation-delay: 1.5s;
}

.star.active:nth-child(5) { 
   animation-delay: 2s;
}

/* ... */

If you have a css precompiler(such as sass), you can achieve it with a loop:

.star.active {
   // change the number 5 to maximum possible stars(8, 10, etc.)
   @for $i from 1 through 5 {
      &:nth-child(#{$i}) {
         animation-delay: #{($i - 1) * 0.5}s;
      }
   }
}
.star {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: solid 1px #000;
  background-color: #eee;
}

.star.active {
  animation: star-pop 0.5s ease forwards;
}


.star.active:nth-child(1) { 
   animation-delay: 0s;
}

.star.active:nth-child(2) { 
   animation-delay: 0.5s;
}

.star.active:nth-child(3) { 
   animation-delay: 1s;
}

.star.active:nth-child(4) { 
   animation-delay: 1.5s;
}

.star.active:nth-child(5) { 
   animation-delay: 2s;
}

@keyframes star-pop {
   to {
      background-color: #000;
   }
}
<div class="rating">
  <div class="star active"></div>
  <div class="star active"></div>
  <div class="star active"></div>
  <div class="star"></div>
  <div class="star"></div>
</div>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x