Home > Software design >  How do I get my nested <ul>s to display as a dropdown when :hover is not working?
How do I get my nested <ul>s to display as a dropdown when :hover is not working?

Time:11-06

I'm working on site navigation, and I'm trying to create a dropdown menu. I have three list items with additional unordered lists that I would like to drop down. However, I am having issues with the :hover pseudo-class. If I do nav ul:hover ul {display: block;} then a dropdown appears, but it occurs whenever I hover over any area of the navigation bar. However, if I code nav li:hover ul {display: block;} then I can't get any dropdown to appear at all. Any advice regarding what I'm doing wrong would be much appreciated.

This is the CSS I'm currently working with:

nav { padding: 0;
      font-size: 100%;
      text-align: center;
      position: relative;
}

nav ul { list-style-type: none;
     margin: 0.5em;
     padding-left: 0;
     font-size: 100%;
}

nav li {border-bottom: 1px solid #002171;}

nav a { text-decoration: none;
    display: block;
}

nav a:hover { color: #A52F00; 
          background-color: #000000; }

nav ul ul { position: absolute;
        display: none;
        padding: 0;
            }

nav ul ul li { display: block;
           background-color: #FFFFFF;
           width: 15em;
           text-align: center;
           margin-left: 0;}

nav li:hover ul { display: block; }

I am using it on the following HTML:

<nav>
    <ul>
      <li><a href="index.html">Home</a></li>
      <li><a href="#">Link 2</a></li>
        <ul>
          <li><a href="#">Drop 1</a></li>
          <li><a href="#">Drop 2</a></li>
          <li><a href="#">Drop 3</a></li>
          <li><a href="#">Drop 4</a></li>
        </ul>
      <li><a href="#">Link 3</a></li>
        <ul>
          <li><a href="#">Link 3 Drop</a></li>
        </ul>
      <li><a href="#">Link 4</a></li>
        <ul>
          <li><a href="#">Link 4 Drop</a></li>
        </ul>
      <li><a href="#">Link 5</a></li>
    </ul>
  </nav>

CodePudding user response:

First of all, the way you're doing this nesting is not correct (as I've previously answered here in Only correct way

This is however, easier to do with JavaScript and CSS, so I have wrote following code, in order to demonstrate of how this should be done (check jsfiddle link below):

CHECK THIS IMAGE

CodePudding user response:

Your li and ul aren't nested correctly.

<li><a></a></li>
// It should be inside the li's everything down there
<ul>
//The dropdown menu
...
</ul>

That should fix the problem.

  • Related