Css Dropdown Menu - Hover disappear

2019-05-28 17:42发布

问题:

When the mouse icon gets on the drop down menus, hover shouldn't be disappearing. How can I do it guys?

Fiddle

.m-navbar ul li{float: left; font-weight: 500; font-size: 20px;margin-left: 25px;list-style:none;}

.m-navbar ul li a{color:#2d3438;border-radius: 4px;padding: 7px 25px;text-decoration:none;}

.m-navbar ul li a:hover{text-decoration: none; background-color: #656a6f;border-radius: 4px;color: #ffc000;}

.m-navbar ul li ul{display: none;width: 200px;float: left;background-color: #ffc000;margin: 9px 0 0 0;position: absolute;padding: 5px 0 ;border-radius:4px;}

.m-navbar ul li:hover ul {display: block;}

.m-navbar ul li ul li a:hover{background-color: #ffc000;color: #ffffff;}
<div class="m-navbar">
  <ul>
    <li>
      <a href="">Home</a>
      <ul>
        <li><a href="#">Laptops</a></li>
        <li><a href="#">Monitors</a></li>
        <li><a href="#">Printers</a></li>
      </ul>
    </li>
    <li>
      <a href="">References</a>
      <ul>
        <li><a href="#">Laptops</a></li>
        <li><a href="#">Monitors</a></li>
        <li><a href="#">Printers</a></li>
      </ul>
    </li>
    <li><a href="">About Me</a> </li>
    <li><a href="">Contact</a></li>
  </ul>
</div>

回答1:

Because of your 9px top margin defined in your CSS there is a gap between the top buttons and the drop down menu. If the mouse triggers over that gap then the hover is cancelled and everything disappears.

Either remove the gap, or replace the gap with an actual element, like an HR element like so:

<li>
    <a href="">Home</a>
    <hr />
    <ul>        
        <li><a href="#">Laptops</a></li>
        <li><a href="#">Monitors</a></li>
        <li><a href="#">Printers</a></li>
    </ul>
</li>

Then edit your CSS and remove the 9px margin from .m-navbar ul li ul

Then create the HR styling:

.m-navbar ul li hr { border: 0px; padding: 0px; margin: 9px 0px 0px 0px; }



回答2:

Just change :

.m-navbar ul li a:hover{text-decoration: none; background-color: #656a6f;border-radius: 4px;color: #ffc000;}

to

.m-navbar ul li:hover > a{text-decoration: none; background-color: #656a6f;border-radius: 4px;color: #ffc000;}

This will do the trick because the :hover is fired only to the <li> element but <a> is no longer hovered



回答3:

Update:

.m-navbar ul li{float: left; font-weight: 500; font-size: 20px;margin-left: 25px;list-style:none;}

By adding a 9px padding-bottom:

.m-navbar ul li{float: left; font-weight: 500; font-size: 20px;margin-left: 25px;list-style:none; padding-bottom: 9px;}

As seen here: http://jsfiddle.net/gzd4ygmd/5/



回答4:

I believe the issue you're facing is because of the gap between your link and the drop down menu, so all you need to do is to give your -navbar ul li a class a margin of zero, so it would look like this:

.m-navbar ul li a{color:#2d3438;border-radius: 4px;padding: 7px 25px;text-decoration:none;margin:0}