Search code examples
cssmenuhoverdropdownsubmenu

Dropdown menu do not working correctly


The submenu is not working correctly. It should appears when hover on specific item, but its appearing when hover any item

HTML

<div class="sty">
    <ul class="met_clean_list">
      <li><a href="#">Link 01</a></li>
        <ul>
          <li><b><a href="#">Sublink 01</a></b></li>
          <li><b><a href="#">Sublink 02</a></b></li>
        </ul>
      <li><a href="#">Link 02</a></li>
      <li><a href="#">Link 03</a></li>
    </ul>          
  </div>

CSS

.sty {
  background:#aaa;
  float:left;
  width:600px;
}


.sty ul li  {
  list-style:none;
  position:relative;
  padding:25px 10px;
  float:left;
}

.sty ul ul{
display:none;
}



.met_clean_list:hover ul {
 display:block;
 background:red;
}

https://jsfiddle.net/59opc6tj/119/


Solution

  • That's because the hover rule you specified doesn't do what you wish it will do.

    You have written: If I hover on .met_clean_list, make all uls within it displayed.

    What you wanted to write: If I hover on one of the lis, make the following ul visible.

    Thus, you should write .met_clean_list li:hover + ul

    .sty {
        background: #aaa;
        float: left;
        width: 600px;
    }
    
    .sty ul li {
        list-style: none;
        position: relative;
        padding: 25px 10px;
        float: left;
    }
    
    .sty ul ul {
        display: none;
    }
    
    .met_clean_list li:hover + ul {
        display: block;
        background: red;
    }
    
    .sty ul ul:hover {
      display: block;
    }
    <div class="sty">
        <ul class="met_clean_list">
            <li><a href="#">Link 01</a></li>
            <ul>
                <li><b><a href="#">Sublink 01</a></b></li>
                <li><b><a href="#">Sublink 02</a></b></li>
            </ul>
            <li><a href="#">Link 02</a></li>
            <li><a href="#">Link 03</a></li>
        </ul>
    </div>

    Notice that I also added:

    .sty ul ul:hover {
        display: block;
    }
    

    So the dropdown won't disappear when you hover on it.