Hover on one element and changing the color of another element

Asked

Viewed 1,860 times

0

I would like when passing the mouse over the green element the pink changed to the blue color.

#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>

1 answer

1

Explaining why it’s not working

The way you did:

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

It would only work if the div "effect" was inside the div "second".

Solution with javascript

You can do this effect 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: https://jsfiddle.net/hkLxpk7e/

Available feature of css

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

A div next to another:

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

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

With one div followed by another, but with others in between.

#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 div "first": https://jsfiddle.net/hkLxpk7e/1/

Source

Solution using only css

You can change the html structure too, this way:

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

Thus it is possible to use only css to create its effect, but make it necessary to manipulate the div "effect" to stay in the upper right corner, in this way:

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

Upshot: https://jsfiddle.net/hkLxpk7e/2/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.