1 Question: How to change span style while hovering a div?

Question created on Sunday February 26, 2017

I'm trying to change the style of a span while hovering on a div, and this div on hover should also change its color.

This is my code so far (the bg of div changes, but the color of span doesn't, why?):

<!DOCTYPE html>
<html>
<head>
    <title>HOME</title>
    <style type="text/css">
        div{
            width: 200px;
            height: 200px;
            background-color: red;
        }
        div:hover{
            background-color: blue;
        }
        span{
            color: blue;
        }
        div:hover span{
            color: green;
        }
    </style>
</head>
<body>

<div></div>
<span>WHY</span>

</body>
</html>

Any help would be really appreciated.

3
3 answer                              3                         

You can use + selector in CSS like following:

div:hover + span {
    color: green;
}

Here is the link of JSFiddle.

0
Sunday February 26, 2017

You need to put span tag inside the div. Something like this:

div{
    width: 200px;
    height: 200px;
    background-color: red;
}
div:hover{
    background-color: blue;
}
span{
    color: blue;
}
div:hover span{
    color: green;
}
<div>
  <span>span text</span>
</div>

3
Sunday February 26, 2017

If you want to use JQuery. this might help you.

$('div').hover(function(){
  $("span").css("background-color","red");
})
0
Sunday February 26, 2017
source posted here