Is there a way to select descending elements?

Viewed 274

I am working for rating with HTML/CSS.

You can check the example below.

ul {
  display: inline-block;
  list-style: none;
  cursor: pointer;
}

ul li {
  color: gray;
  display: inline-block;
  padding: 5px;
}

ul li:hover, li:hover ~ li {
  background-color: red;
  color: white;
}
<ul>
  <li>@</li>
  <li>@</li>
  <li>@</li>
  <li>@</li>
  <li>@</li>
</ul>

As you see, when I hover the li, I am getting sibling elements are getting red. Instead I wanted descending elements are getting red.

And I don't want my rating is displayed with inverted color - like all red but selections are gray. This is not what I wanted.

Thanks

4 Answers

ul {
  display: inline-block;
  list-style: none;
  cursor: pointer;
}

ul li {
  color: gray;
  display: inline-block;
  padding: 5px;
  float: right;
}

ul li:hover, li:hover ~ li {
  background-color: red;
  color: white;
}
<ul>
  <li>@</li>
  <li>@</li>
  <li>@</li>
  <li>@</li>
  <li>@</li>
</ul>

How about adding float: right; for ul li? I think this is the way you wanted. Thanks

ul {
  display: flex;
  flex-direction: row-reverse;
  justify-content: center;
  align-items: center;
  list-style: none;
  cursor: pointer;
}

ul li {
  color: gray;
  padding: 5px;
}

ul li:hover, li:hover ~ li {
  background-color: red;
  color: white;
}
<ul>
  <li>@</li>
  <li>@</li>
  <li>@</li>
  <li>@</li>
  <li>@</li>
</ul>

How about using flex? It provides row-reverse. Thanks

Here's an alternative method, in case the order of ratings must be left intact.

I'm setting all ratings to "selected" when the <ul> is hovered over.
Then, I set siblings that follow the hovered <li> element back to "unselected".

ul {
  display: inline-flex;
  list-style: none;
  cursor: pointer;
  margin: 0;
  padding: 0;
}

ul li {
  color: gray;
  padding: 5px;
}

ul:hover li {
  background-color: red;
  color: white;
}

li:hover ~ li {
  background-color: transparent;
  color: gray;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

Try with below code :

let li = document.getElementsByTagName('li');
for (let itm = li.length; i-- ;) {
   // reverese li are available here. put your logic here like below
   // li[i].parentNode.appendChild(li[i]);
}
Related