3

I got two div's and I want to change the color of the first by hovering the second one. I found solutions when the "hovered " come before the objective that its css should be changed, what if the "hovered" come after? What could be done without javascript?

.box, .box-2 {
  display: block;
  height: 100px;
  width: 100px;
  margin: 20px;
}

.box {
  background-color: red;
}

.box-2 {
  background-color: blue;
}

.box-2:hover + .box {
  background-color: green;
}
<body>
<div class="wrapper"> 
  <div class="box"></div>
  <div class="box-2"></div>
</div>
</body>
SaidbakR
  • 13,303
  • 20
  • 101
  • 195
Heitor Giacomini
  • 384
  • 2
  • 12

2 Answers2

3

A solution is to inverse the order visually and keep the order in the DOM so that you can still use the + selector.

Here is an example with flex:

.wrapper {
  display:flex;
  flex-direction:column;
}

.box, .box-2 {
  display: block;
  height: 100px;
  width: 100px;
  margin: 20px;
}

.box {
  background-color: red;
}

.box-2 {
  background-color: blue;
  order:2; /* this will make box-2 goes after */
}

.box-2:hover + .box {
  background-color: green;
}
<body>
<div class="wrapper"> 
  <div class="box-2"></div>
  <div class="box"></div>
</div>
</body>

Some related question to get more ideas:

Is there a "previous sibling" CSS selector?

Previous adjacent sibling selector workaround?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
1

While Temani's answer is a great technique, I have an alternative suggestion if you need this to work both ways, using the :not() selector, though it's a tad bit more hit-or-miss because of your margins.

If you check for the hover on the .wrapper element, you can then style your box when it isn't hovered, like so:

.wrapper:hover > .box:not(:hover) {
    background-color: green;
}
chriskirknielsen
  • 2,839
  • 2
  • 14
  • 24