1

Goals:

  • When hovering on .one I want both .two and .three to use the same BG image.
  • When hovering on .two I want both .one and .three to use the same BG image.
  • When hovering on .three I want both .one and .two to use the
    same BG image.

It seems like the sibling selector doesn't allow previous sibling elements on :hover. Is there a solution for this?

.item{
  width: 200px;
  height: 200px;
  float: left;
  margin: 15px;
  cursor: pointer;
  transition: all .3s ease;
}

.one,
.one:hover ~ .two,
.one:hover ~ .three{
  background: url('https://placeimg.com/200/200/nature');
}

.two,
.two:hover ~ .one,
.two:hover ~ .three{
  background: url('https://placeimg.com/200/200/arch');
}

.three,
.three:hover ~ .one,
.three:hover ~ .two{
  background: url('https://placeimg.com/200/200/tech');
}
<div class="item one"></div>
<div class="item two"></div>
<div class="item three"></div>

UPDATE: Looks like there is no CSS solution for this but I did create a jQuery solution.

$('.one').hover(
 function(){ $('.two, .three').addClass('one-all') },
  function(){ $('.two, .three').removeClass('one-all') }  
);

$('.two').hover(
 function(){ $('.one, .three').addClass('two-all') }, 
  function(){ $('.one, .three').removeClass('two-all') }    
);

$('.three').hover(
 function(){ $('.one, .two').addClass('three-all') },   
  function(){ $('.one, .two').removeClass('three-all') }    
);
.item{
  width: 200px;
  height: 200px;
  float: left;
  cursor: pointer;
  transition: all .3s ease;
}

/* original images */
.one{ background: url('https://placeimg.com/200/200/nature');}
.two{ background: url('https://placeimg.com/200/200/arch');}
.three{ background: url('https://placeimg.com/200/200/tech');}

/* replacement images*/
.one-all{ background: url('https://placeimg.com/200/200/nature');}
.two-all{ background: url('https://placeimg.com/200/200/arch');}
.three-all{ background: url('https://placeimg.com/200/200/tech');}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item one"></div>
<div class="item two"></div>
<div class="item three"></div>
Daniel Theman
  • 145
  • 2
  • 13
  • 1
    Possible duplicate of [Is there a "previous sibling" CSS selector?](https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-css-selector) – Phiter Apr 23 '18 at 18:01

1 Answers1

1

Sadly, there is no "previous sibling" selector in CSS (see the complete list).

Note that it is possible to play with the Flexbox order property to simulate previous sibling selection but next sibling selection can't be applied thereafter.

You'll need to go JavaScript on this one.

VXp
  • 11,598
  • 6
  • 31
  • 46
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84