0

I want, when the first class hover, the second class's color is white.

<div class="diva">This is the first class</div>

<div class="divb">This is the second class</div>

<style>
.diva:hover .divb {
  color:#fff;
}
</style

but, this isn't work. How can I do this?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Peter6528
  • 43
  • 1
  • 5

2 Answers2

1

You're looking for the adjacent sibling selector (CSS 2.1) +. To quote the specs

The + selector matches if E1 and E2 share the same parent in the document tree and E1 immediately precedes E2

.diva:hover + .divb {
  color: #fff;
  background-color: green;
  padding-left: 4em;
}
<div class="diva">Hover over first div to change color of sibling</div>
<div class="divb">This is the second class</div>
surfmuggle
  • 5,527
  • 7
  • 48
  • 77
andi
  • 6,442
  • 1
  • 18
  • 43
  • For future reference, please look for duplicates to close against for extremely common questions such as these, rather than answering them. – Serlite Oct 31 '16 at 19:46
  • 1
    I didn't agree that the question you listed above was a duplicate. – andi Oct 31 '16 at 19:47
  • That's fine, then feel free to pose an alternative duplicate. Additionally, did you read beyond the accepted answer? The highest-voted answer shows exactly how to do this. – Serlite Oct 31 '16 at 19:48
  • yes, I read the answer that describes this, but I feel that a question shouldn't be marked as a duplicate unless the questions are equivalent, not just when one given answer can help solve the problem. – andi Nov 01 '16 at 15:54
  • Sure, that's a completely valid view. For a question like this though, there were plenty of other duplicates you could suggest for this to be closed against, which is more useful to future visitors than having scattered answers of varying completeness across multiple questions. (Eg. http://stackoverflow.com/questions/6867257/is-there-any-way-to-hover-over-one-element-and-affect-a-different-element or the related http://stackoverflow.com/questions/4502633/how-to-affect-other-elements-when-a-div-is-hovered) Just something to keep in mind for the future. – Serlite Nov 01 '16 at 16:06
1

The CSS 3 general sibling combinator ~ can be used in your case for providing hover effect for another class.

The elements [E1 ~ E2] represented by the two sequences share the same parent in the document tree and the element represented by the first sequence [E1] precedes (not necessarily immediately) the element represented by the second one [E2].

Below code set the font color white for divb if the user hovers over diva. This combinator can be used if elements are not in adjacent position

<html>
   <body>
      <div class="diva">Hover over the first element</div>
      <div class="divb">I will change my color</div>
      <style>
         .diva:hover ~ .divb {
         color:#fff;
         }
      </style>
</html>
surfmuggle
  • 5,527
  • 7
  • 48
  • 77
GIRISH kuniyal
  • 740
  • 1
  • 5
  • 14