How can I alter sibling element CSS on hover

In the example below when we hover a row, it changes colour. Ideally when any of the red rows are hovered, ALL of the red rows should highlight (and likewise for the blue rows).

How can this be achieved with pure css?

.red-row:hover {
  background-color: red;
}

.blue-row:hover {
  background-color: blue;
}
<body>
  <p class="red-row">Red Row</p>
  <p class="red-row">Red Row</p>
  <p class="red-row">Red Row</p>
  <p class="blue-row">Blue Row</p>
  <p class="blue-row">Blue Row</p>
  <p class="blue-row">Blue Row</p>
</body>

>Solution :

Use the :has() rule on the parent, so if the parent has a child with the same class that is hovered, all other children with the same class would be highlighted.

Note: :has() is not yet supported by Firefox.

.parent:has(.red-row:hover) .red-row {
  background-color: red;
}

.parent:has(.blue-row:hover) .blue-row {
  background-color: blue;
}
<div class="parent">
  <p class="red-row">Red Row</p>
  <p class="blue-row">Blue Row</p>
  <p class="red-row">Red Row</p>
  <p class="blue-row">Blue Row</p>
  <p class="red-row">Red Row</p>
  <p class="blue-row">Blue Row</p>
</div>

Leave a Reply