Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading