Search code examples
csshoverpseudo-class

drop down list does not work html css


I have a problem and can't solve it. I have created this HTML page, but the :hover selector on #drop doesn't work.

#drop {
    display: inline-block;
    color: white;
    background-color: #4CAF50;
    padding: 10px;
}
#droplist {
    display: none;
    position: absolute;
    z-index: 1;
}
#droplist a {
    display: block;
    text-decoration: none;
    color: white;
    background-color: olivedrab;
    padding: 10px;
}
#drop:hover #droplist {
    display: block;
}
#droplist a:hover {
    background-color: olive;
}
<!DOCTYPE html>
<html lang="it">
<!--   ...   -->
<body>
    <div id="pagina">
        <div id="drop">Hover for open the menu</div>
        <div id="droplist">
            <a href="#a">Link 1</a>
            <a href="#b">Link 2</a>
            <a href="#c">Link 3</a>
        </div>
        <br/>text text text text text text text text text
    </div>
</body>
</html>

I try to hover over the div with id #drop but the element #droplist doesn't show up.


Solution

  • You can't select #drop:hover #droplist because #droplist is not a child of #drop.

    Use #drop:hover + #droplist instead.

    the element1 + element2 selector is used to select and style every element2 that are placed immediately after element1

    #drop {
      display: inline-block;
      color: white;
      background-color: #4CAF50;
      padding: 10px;
    }
    
    #droplist {
      display: none;
      position: absolute;
      z-index: 1;
    }
    
    #droplist a {
      display: block;
      text-decoration: none;
      color: white;
      background-color: olivedrab;
      padding: 10px;
    }
    
    #drop:hover+#droplist {
      display: block;
    }
    
    #droplist a:hover {
      background-color: olive;
    }
    
    #droplist:hover {
      display: block
    }
    <!DOCTYPE html>
    <html lang="it">
    <!--   ...   -->
    
    <body>
      <div id="pagina">
        <div id="drop">Hover for open the menu</div>
        <div id="droplist">
          <a href="#a">Link 1</a>
          <a href="#b">Link 2</a>
          <a href="#c">Link 3</a>
        </div>
      </div>
    </body>
    
    </html>

    EDIT: you might want to add in

    #droplist:hover {
       display: block
    }
    

    so that the drop down menu doesn't disappear, when you hover it