8

I know it can be done in JavaScript, however I am looking for solution in CSS.

I have three divs.

  • div#hide should be visible by default, #show should be hidden.
  • When I hover on #main, #hide should hide and #show should be visible.

div#show works fine but #hide doesn't hide when #main is hovered. How can we do it in css?

#show {
  display: none
}
#main:hover + #show {
  display: block
}
#main:hover + #hide {
  display: none
}
<div id="main">
  Hover me
</div>
<div id="show">
  Show me on hover
</div>
<div id="hide">
  Hide me on hover
</div>
Imad
  • 7,126
  • 12
  • 55
  • 112

4 Answers4

18

Instead of + you want to use ~ combinator for hide element because + selects only next-sibling

#show {
  display: none
}
#main:hover + #show {
  display: block
}
#main:hover ~ #hide {
  display: none
}
<div id="main">
  Hover me
</div>
<div id="show">
  Show me on hover
</div>
<div id="hide">
  Hide me on hover
</div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

You just have to replace the + selector with ~ cause the #hide is not placed after #main

So your code is:

#show {display:none}
#main:hover + #show { display:block }
#main:hover ~ #hide { display:none }
Humble Potato II
  • 161
  • 1
  • 1
  • 12
0

You've to use tilda '~' for this case.

The difference between + and ~ is that ~ matches all following siblings regardless of their proximity from the first element, as long as they both share the same parent.

    #show {display:none}
    #main:hover + #show { display:block }
    #main:hover ~ #hide { display:none }
Shuvo Habib
  • 2,035
  • 1
  • 20
  • 25
0

Try something like this: "#main:hover + #show + #hide"

div#show {
    display:none;
}
#main:hover + #show {
    display:block 
}
#main:hover + #show + #hide {
    display:none
}

It's working for me.

Mukesh Ram
  • 6,248
  • 4
  • 19
  • 37