Skip to content Skip to sidebar Skip to footer

Previous Adjacent Sibling Selector Workaround?

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 work

Solution 1:

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;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><figure><divclass="a">
    A
  </div><divclass="b">
    B
  </div></figure>

References

.hover()

.toggleClass()

Solution 2:

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;
}
<figureclass='parent'><divclass="a">
        A
    </div><divclass="b">
        B
    </div></figure>

Post a Comment for "Previous Adjacent Sibling Selector Workaround?"