Heitor Giacomini
Heitor Giacomini

Reputation: 484

Changing property of an element on hover of another element after it

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>

Upvotes: 3

Views: 452

Answers (2)

chriskirknielsen
chriskirknielsen

Reputation: 2929

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;
}

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 272842

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?

Upvotes: 3

Related Questions