0

I'm trying to find out if it's possible to change the color of my whole <ul> list when an <li> is hovered.

The caveat is that I want each <li> child to change the <ul> a different color. For example, the first li hovered will change itself and all its siblings red, the second li hovered will change itself and siblings blue, etc. I can get all the siblings to change color when a single <li> is hovered, but I can't seem to make it work with nth-child.

Edit: I did read through this thread but I'm not seeing specifically how it can be combined with nth-child.

Here is the code that I'm working with so far:

    /*when child is hovered, parent will change to this color*/
    ul:hover > li a {
    color: var(--apricot); 
    }
    
    /*when child is hovered, child will change to this color*/
       ul:hover li:nth-child(1) a:hover { 
         color: var(--apricot) !important; 
       }

Is there any way to make this work so that the siblings will change a different color depending on what child is hovered?

prujuno
  • 33
  • 5

1 Answers1

3

You may use the :has() pseudo class to achieve it, but it worth noting that some old browsers and Firefox might not work.

ul:has(li:nth-child(1):hover) {
  color: red;
}

ul:has(li:nth-child(2):hover) {
  color: blue;
}

ul:has(li:nth-child(3):hover) {
  color: green;
}

ul:has(li:nth-child(4):hover) {
  color: yellow;
}
<ul>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
</ul>
TylerH
  • 20,799
  • 66
  • 75
  • 101
Hao Wu
  • 17,573
  • 6
  • 28
  • 60