1

In this example when a paragraph is hovered over its color is changed to blue, I would like all sibling paragraphs to also have this rule applied. Is there a way I can achieve this CSS?

I have the desired functionality working in JavaScript with jQuery, but would like a pure CSS solution.


Edit: It wasn't clear in my original post, this should apply to only select elements. See the updated HTML.

$(".groupHover").hover(
  function() {
    $(".groupHover").addClass("hoverClass");
  },
  function() {
    $(".groupHover").removeClass("hoverClass");
  }
);
.hoverClass {
  color: red;
}

.groupHover:hover {
  color: blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<p class=>Not to be changed!</p>
<p class="groupHover">Line 1</p>
<p class="groupHover">Line 2</p>
<p class=>Not to be changed!</p>
<p class="groupHover">Line 3</p>
<p class="groupHover">Line 4</p>
<p class=>Not to be changed!</p>
Pete
  • 57,112
  • 28
  • 117
  • 166

1 Answers1

3

Wrap them in a div and put the hover effect on that:

.wrapper:hover .groupHover {
  color: red;
}

.wrapper:hover .groupHover:hover {
  color: blue;                      /* try not to use important - it should only be used if you desperately need to override an inline style you have no control over */
}
<div class="wrapper">
  <p class="groupHover">Line 1</p>
  <p class="groupHover">Line 2</p>
  <p class="">No class, stays black</p>
  <p class="groupHover">Line 3</p>
  <p class="groupHover">Line 4</p>
</div>
Pete
  • 57,112
  • 28
  • 117
  • 166
  • Hey Pete, I apologize my original post was not clear. This should not apply for ALL children, but only those with the group hover class. –  Jan 19 '18 at 16:59
  • @JacobPersi this does only apply to the group hover items, none group hover stays black – Pete Jan 19 '18 at 17:00
  • Your update is what I needed, thank you for the assistance. –  Jan 19 '18 at 17:01
  • One thing to note is that even when hovering over the no-class item, the others get the hover effect. Is there a way to solve this? –  Jan 19 '18 at 17:12
  • 1
    I think you would need to stick with the js for that as unfortunately there is no parent or previous siblings selectors which you would need in order to know you are hovering a p that is not group and not to change it's other siblings – Pete Jan 19 '18 at 17:16