Hide element on hover of another element

前端 未结 4 705
醉梦人生
醉梦人生 2021-01-19 23:21

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
相关标签:
4条回答
  • 2021-01-20 00:12

    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 }
    
    0 讨论(0)
  • 2021-01-20 00:17

    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.

    0 讨论(0)
  • 2021-01-20 00: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>

    0 讨论(0)
  • 2021-01-20 00:18

    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 }
    
    0 讨论(0)
提交回复
热议问题