Search code examples
htmlcssmenusubmenu

how to make menu on mouse hover in CSS


I have a menu. I need to show the submenus when I mouse hover on them. I have some code as follows. But the submenus overlaps with existing menu.

Following is my code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>CSS Drop Down Menus</title>

  <style type="text/css">
    * {
      margin: 0;
      padding: 0;
    }
    body {
      font-family: "Trebuchet MS", Helvetica, Sans-Serif;
      font-size: 14px;
    }
    a {
      text-decoration: none;
      color: #838383;
    }
    a:hover {
      color: black;
    }
    #menu {
      position: relative;
      margin-left: 30px;
    }
    #menu a {
      display: block;
      width: 140px;
    }
    #menu ul {
      list-style-type: none;
      padding-top: 5px;
    }
    #menu li {
      float: top;
      position: relative;
      padding: 3px 0;
      text-align: center;
    }
    #menu ul.sub-menu {
      display: none;
      position: absolute;
      top: 20px;
      left: -10px;
      padding: 10px;
      z-index: 90;
    }
    #menu ul.sub-menu li {
      text-align: top;
    }
    #menu li:hover ul.sub-menu {
      display: block;
      border: 1px solid #ececec;
    }
  </style>
</head>
<body>
<div id="menu">
  <ul>
    <li><a href="#">Home</a>
      <ul class="sub-menu">
        <li><a href="#">Pages</a></li>
        <li><a href="#">Archives</a></li>
        <li><a href="#">New Posts</a></li>
        <li><a href="#">Recent Comments</a></li>
      </ul>
    </li>
    <li><a href="#">About</a>
      <ul class="sub-menu">
        <li><a href="#">Get to know us</a></li>
        <li><a href="#">Find out what we do</a></li>
      </ul>
    </li>
    <li><a href="#">Contact</a>
      <ul class="sub-menu">
        <li><a href="#">E-mail Us</a></li>
        <li><a href="#">Use Our Contact Form</a></li>
      </ul>
    </li>
  </ul>
</div>
</body>
</html>

I need some effect like this. enter image description here

How can I make it.


Solution

  • You've set left: -10px on #menu ul.sub-menu, which is why it's overlapping #menu. You should set that to a value that'll move it far enough to the right for your purposes, perhaps left: 140px since that's the width of the menu div.