Search code examples
htmlcsshtml-listsnavpseudo-class

Why isn't my submenu displaying under my nav element?


I'm using the Murach HTML5/CSS3 book for a project and have gotten a two-tier navigation menu to work as instructed before. However, using the same method in the book doesn't seem to be working in this case. The nav is supposed to be a horizontal menu and a vertically aligned submenu upon hover.

I've tried eliminating other stylesheets, and several combinations of changing different selectors' display properties.

<nav id="nav_menu">
<ul>
  <li><a href="index.html">Home</a></li>
  <li><a href="nav/ingredients.html">Ingredients</a></li>
    <ul>
      <li><a href="nav/fish.html">Fish</a></li>
      <li><a href="nav/vegetables.html">Vegetables</a></li>
      <li><a href="nav/condiments.html">Condiments</a></li>
      <li><a href="nav/others.html">Others</a></li>
   </ul>
    <li><a href="nav/history.html">History</a></li>
    <li><a href="nav/trivia.html">Trivia</a></li>
    <li><a href="nav/types.html">Types</a></li>
</ul>

#nav_menu {
clear: left;
}

#nav_menu ul {
list-style: none;
position: relative;
width: 100%;
}

#nav_menu ul li {
float: left;
width: 20%;
}

#nav_menu ul li a {
text-align: center;
padding: .7em 0;
background-color: #5a5a5a;
font-weight: bold;
color: white;
text-decoration: none;
}

#nav_menu ul ul {
display: none;
position: absolute;
top: 100%;
}

#nav_menu ul ul li {
float: none;
}

#nav_menu ul li:hover > ul {
display: block;
}


#nav_menu > ul:after {
content: "";
display: block;
clear: both;
}

#nav_menu a:hover {
background-color: crimson;
color: black;
}

#nav_menu ul li a.current {
color: black;
}
#nav_menu ul li a:hover, #nav_menu ul li a:focus {
background-color: crimson;
}

The submenu ul child of li Ingredients should display underneath upon hover.


Solution

  • The submenu is not displayed when hovering, because your CSS cant find the submenu.

    CSS is looking for the first ul in the li hovered:

        #nav_menu ul li:hover > ul {
        display: block;
        }
    

    But there is none, as your submenu ul follows the li and is not within in.

        <li><a href="nav/ingredients.html">Ingredients</a></li>
        <ul>
    

    If you change the HTML, your CSS works:

        <li><a href="nav/ingredients.html">Ingredients</a>
        <ul>
          <li><a href="nav/fish.html">Fish</a></li>
          <li><a href="nav/vegetables.html">Vegetables</a></li>
          <li><a href="nav/condiments.html">Condiments</a></li>
          <li><a href="nav/others.html">Others</a></li>
       </ul></li>