1

#myUserMenu {
  position: absolute;
  background-color: white;
  top: 20px;
  width: 116px;
  border: 1px solid #CCC;
}
#myAvatar:hover #myUserMenu {
  background-color: red;
}
.menuItem {
  cursor: pointer;
  border-bottom: 1px solid #EEE;
}
<img id='myAvatar'>some text here...
<div id="myUserMenu">
  <div class='menuItem'>Status online</div>
  <div class='menuItem'>Status offline</div>
</div>

So when I hover the myAvatar, myUserMenu background should change to red

#myAvatar:hover #myUserMenu

And nothing happens ! Any idea why ?

Suresh Karia
  • 17,550
  • 18
  • 67
  • 85
yarek
  • 11,278
  • 30
  • 120
  • 219

4 Answers4

2

Enclose the text inside a span and use + operator to affect the next element's style.

#myUserMenu {
  position: absolute;
  background-color: white;
  top: 20px;
  width: 116px;
  border: 1px solid #CCC;
}
#myAvatar:hover + #myUserMenu {
  background-color: red;
}
.menuItem {
  cursor: pointer;
  border-bottom: 1px solid #EEE;
}
<span id="myAvatar">some text here...</span>
<div id="myUserMenu">
  <div class='menuItem'>Status online</div>
  <div class='menuItem'>Status offline</div>
</div>
m4n0
  • 29,823
  • 27
  • 76
  • 89
1
#myAvatar:hover #myUserMenu {
    background-color: red;
}

This selector is looking for #myUserMenu inside #myAvatar. Obviously that won't work because it's outside #myUserMenu.

What you could do is look for #myUserMenu immediately after #myAvatar, like so:

#myAvatar:hover + #myUserMenu {
    background-color: red;
}

This is the Adjacent Sibling Combinator. See this article for more details.

Or you could rearrange your HTML to put #myUserMenu inside #myAvatar.

Olly Hodgson
  • 15,076
  • 3
  • 40
  • 60
0

Your div #myUserMenu is not a child of your image, so you need to target the div with a brother selector :

#myAvatar:hover ~ #myUserMenu {
    background-color:red;
}

JsFiddle: http://jsfiddle.net/ghorg12110/o0c2hppv/

The general sibling combinator selector ~ allow you to select the element which can appear anywhere after it.

Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35
-1

You have to apply parent child relationship in order to apply hover.

Like this

#myUserMenu {
  position: absolute;
  background-color: white;
  top: 20px;
  width: 116px;
  border: 1px solid #CCC;  
}
#myAvatar:hover #myUserMenu {
    background-color:red;
}

.menuItem {
    cursor:pointer;
    border-bottom:1px solid #EEE;
}
<div id="myAvatar">
<img id=''> some text here...
    <div id="myUserMenu">
        <div class='menuItem'>Status online</div>
        <div class='menuItem'>Status offline</div> 
    </div>
</div>
Suresh Karia
  • 17,550
  • 18
  • 67
  • 85