I want to create star rating by CSS. When user will hover last star, all stars before that star must have another color, e.g.: I will hover minStar3, then minStar1,minStar2 and minStar3 must have different color.
<i id="minStar1" class="fa fa-star fa-lg" aria-hidden="true"></i>
<i id="minStar2" class="fa fa-star fa-lg" aria-hidden="true"></i>
<i id="minStar3" class="fa fa-star fa-lg" aria-hidden="true"></i>
<i id="minStar4" class="fa fa-star fa-lg" aria-hidden="true"></i>
<i id="minStar5" class="fa fa-star fa-lg" aria-hidden="true"></i>
You could create this with Flexbox
and change order of elements with flex-direction: row-reverse
. You can also use ~
general sibling selector to select all sibling elements that come after hovered element .
.rating {
display: inline-flex;
flex-direction: row-reverse;
}
i {
width: 20px;
height: 20px;
margin: 5px;
border: 1px solid black;
transition: all 0.3s ease-in;
}
i:hover ~ i,
i:hover {
background: black;
}
<div class="rating">
<i id="minStar1" class="fa fa-star fa-lg" aria-hidden="true"></i>
<i id="minStar2" class="fa fa-star fa-lg" aria-hidden="true"></i>
<i id="minStar3" class="fa fa-star fa-lg" aria-hidden="true"></i>
<i id="minStar4" class="fa fa-star fa-lg" aria-hidden="true"></i>
<i id="minStar5" class="fa fa-star fa-lg" aria-hidden="true"></i>
</div>
I have seen this trick before here on SO, but can't find it back.
To do so, invert the order of the stars.
Wrap them in an element (like a p
or a div
)
Give that wrapper direction: rtl
.
By inverting the direction, the ~
sibling selector can be used.
i {
display: inline-block;
width: 50px;
height: 50px;
background: green;
}
p {
text-align: left;
direction: rtl;
}
p>i:hover,
p>i:hover~i {
background: red;
}
<p>
<i id="minStar5" class="fa fa-star fa-lg" aria-hidden="true">5</i>
<i id="minStar4" class="fa fa-star fa-lg" aria-hidden="true">4</i>
<i id="minStar3" class="fa fa-star fa-lg" aria-hidden="true">3</i>
<i id="minStar2" class="fa fa-star fa-lg" aria-hidden="true">2</i>
<i id="minStar1" class="fa fa-star fa-lg" aria-hidden="true">1</i>
</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With