Hover in one element and changing the color of another element

0

I would like to move the mouse over the green element to change the color to blue.

#primeiro{
  width: 300px;
  height: 300px;
  background: red;
   float: left; 
}
#segundo{
  width: 150px;
  height: 150px;
  background: green;
  margin: auto; 
}
#segundo:hover #efeito{
  background: blue;
}
#efeito{
  width: 90px;
  height: 90px;
  background: pink;
  float: left; 
}
<div id="primeiro"><div id="segundo"></div></div>

<div id="efeito"></div>
    
asked by anonymous 28.12.2017 / 12:27

1 answer

1

Explaining why it is not working

The way you did it:

#segundo:hover #efeito{
  background: blue;
}

It would only work if the "effect" div were within the "second" div.

Solution with javascript

You can do this using javascript:

var segundo = document.getElementById("segundo");
var efeito = document.getElementById("efeito");

segundo.addEventListener("mouseover", mouseOver);
segundo.addEventListener("mouseout", mouseOut);

function mouseOver() {
    efeito.style.background = "blue";
}

function mouseOut() {
    efeito.style.background = "pink";
}

Example: link

Available css feature

I just found a way to do it using css only, but this way the div has to be in the same "height" as the other, as the "second" div is inside the "first" div will no longer work, would work if the hover would be in the "first" div since the "effect" div comes after it.

One div followed by another:

#a:hover + #b {
    background: #ccc
}

<div id="a">Div A</div>
<div id="b">Div B</div>

With one div followed by the other, but with others in the middle.

#a:hover ~ #b {
    background: #ccc
}

<div id="a">Div A</div>
<div>random other elements</div>
<div>random other elements</div>
<div>random other elements</div>
<div id="b">Div B</div>

Example using the "first" div: link

Source

Solution using css only

You can change the html structure too, like this:

<div id="primeiro">
  <div id="segundo"></div>
  <div id="efeito">sd</div>
</div>

So you can only use css to create your effect, but make it necessary to manipulate the "effect" div to be in the upper right corner, like this:

#primeiro{
  width: 300px;
  height: 300px;
  background: red;
   float: left; 
}
#segundo{
  width: 150px;
  height: 150px;
  background: green;
  margin: auto; 
}
#efeito{
  width: 90px;
  height: 90px;
  background: pink;
  float: left; 
  position:absolute;
  margin-left:300px;
  top:8px;
}
#segundo:hover ~ #efeito {
    background: blue
}

Result: link

    
28.12.2017 / 12:42