4

I have two adjacent selectors that I would like to effect when hovering over the other. In the example below, the two selectors should effect the others CSS when hovered. This works perfectly when hovering .a, but not when hovering .b. I realize this is because the DOM is read in order, and therefore CSS selectors cannot work backwards.

However, is there a jQuery workaround (or any other suggestions) that can achieve this effect?

Here is a Fiddle

Thanks.

HTML

<figure>
    <div class="a">
        A
    </div>
    <div class="b">
        B
    </div>
</figure>

CSS

.a {
    width: 100px;
    height: 100px;
    background: red;
}

.b {
    width: 100px;
    height: 100px;
    background: blue;
}

.a:hover ~ .b {
    background: green;
}

.b:hover ~ .a { /* This one doesn't work */
    background: green;
}
Kristijan Iliev
  • 4,901
  • 10
  • 28
  • 47
dungey_140
  • 2,602
  • 7
  • 34
  • 68

2 Answers2

5

There isn't css previous element selector.

.b:hover ~ .a { /* This one doesn't work */
    background: green;
}

General sibling combinator:

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

One solution is using jquery .prev():

$(".b").hover(function() {
  //using prev selector and toggleClass
  $(this).prev().toggleClass("active");
});
.a {
  width: 100px;
  height: 100px;
  background: red;
}
.b {
  width: 100px;
  height: 100px;
  background: blue;
}
.a:hover ~ .b {
  background: green;
}
.active {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<figure>
  <div class="a">
    A
  </div>
  <div class="b">
    B
  </div>
</figure>

References

.hover()

.toggleClass()

Alex Char
  • 32,879
  • 9
  • 49
  • 70
  • 1
    Thanks @Alex_Char - This is great but in my current setup the pure css parent example below is more practical. I was open to using jQuery but now it doesn't seem necessary. Im sure this answer will be very useful for others though, so thank you. – dungey_140 Oct 05 '15 at 12:26
3

There's no previous selector in css. One way is to implement it wiht jQuery like @Alex Char pointed out, and other way is with hover on parent, instead the actual items, with pure css like this:

.a {
    width: 100px;
    height: 100px;
    background: red;
}
.b {
    width: 100px;
    height: 100px;
    background: blue;
}

.parent{             /* ADDED */
    width: 100px;
}

.parent:hover > div:not(:hover) {   /* ADDED */
    background: green;
}
<figure class='parent'>
    <div class="a">
        A
    </div>
    <div class="b">
        B
    </div>
</figure>
Kristijan Iliev
  • 4,901
  • 10
  • 28
  • 47