How can I set the color of other children based on if one of them has a class? [duplicate]

The desired behavior is - when a child is hovered, all other children should be greyed out. I can't really wrap my head around the structure and the selectors.

As such, given:

<div class="parent">
  <div class="child">
  <div class="child">
  <div class="child">
</div>

If all .child items had a color: black by default, then .child:hover should be color: red, however, basically (pseudo-code) .child:not(:hover) should be color: grey, the problem with this approach is that it overwrites the default black to grey (since, by default, all items are not hovered when the structure renders, so, it needs to have a check of "after you've hovered one item" of some sorts).

JS can be used. I've tried to add classes to the other children with JS, play with just the hover class itself and so on, but to no avail.

Would appreciate some help.


Solution 1:

When a child is hovered its parent is hovered too so you can use this fact to set the color.

In this snippet parent sets color to black. When it is hovered it sets it to gray.

This is overridden for the child that is being hovered by setting the color back to black (or could be whatever color you want to highlight the hovered one).

.parent {
  color: black;
}

.parent:hover {
  color: gray;
}

.child:hover {
  color: black;
}
<div class="parent">
  <div class="child">Child 1</div>
  <div class="child">Child 2</div>
  <div class="child">Child 3</div>
</div>