This was an interview question I was asked from Amazon. The question is to use HTML and css only to apply some css to the first n elements when hovering the nth element. i.e. You have 5 grey stars on the page, and when you hover the 4th star, the first 4 stars change to yellow, just like the rating UI on Amazon.
Asked
Active
Viewed 196 times
0
-
there is a lot of way to achieve this, we need more context as this is actually too broad ... but the duplicate will give you many workarounds – Temani Afif Sep 23 '18 at 20:40
-
Basically you need to learn the use of the ~ CSS selector. Here's an example I made: https://codepen.io/anon/pen/wEZNra – Mark Sep 23 '18 at 21:19
1 Answers
2
You can use a flexbox with flex-direction: row-reverse
and the general sibling combinator ~
. The siblings selector will effect all siblings that come after the hovered the item, and the reversed flexbox will display them before the hovered item.
.container {
display: inline-flex;
flex-direction: row-reverse;
list-style: none;
}
.container li:hover, .container li:hover ~ li {
color: red;
}
<ul class="container">
<li>X</li>
<li>X</li>
<li>X</li>
<li>X</li>
<li>X</li>
</ul>

Ori Drori
- 183,571
- 29
- 224
- 209