kappa322 kappa322 - 6 months ago 10
CSS Question

Dropdown menus on hover and lists

I am currently attempting to create a vertical navigation bar using lists, however I am running into problems where when I hover over the ul, all the dropdown menus in the li show up or they don't show up at all. Is there a solution to this?

HTML:

<body>
<div class="navbar">
<ul>
<li>title</li>
<li>main text</li>
<div class="dropdown-content">
<a href="#">text</a>
<a href="#">text</a>
<a href="#">text</a>
</div>
<li>main text</li>
<div class="dropdown-content">
<a href="#">text</a>
<a href="#">text</a>
<a href="#">text</a>
</div>
<li>main text</li>
<div class="dropdown-content">
<a href="#">text</a>
<a href="#">text</a>
<a href="#">text</a>
</div>
</ul>
</div>
</body>


CSS:

.dropdown {
position: relative;
display: inline-block;
}

.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
border-radius: 15px;
}

.dropdown-content a {
padding: 12px 16px;
text-decoration: none;
display: block;
}

.dropdown-content a:hover {
background-color: #f1f1f1;
border-radius: 15px;
}

.navbar ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
border: 1px solid #000000;
float: left;
border-radius: 25px;
background-color: #9cddf0;
height: 500px;
overflow: hidden;
line-height: 35px;
}

.navbar ul li {
display: block;
color: #000000;
padding: 0px;
text-decoration: none;
text-align: left;
padding-left: 5px;
}

.navbar ul:hover .dropdown-content {
display: block;
}


On the last three lines of the CSS, if I change it to
.navbar ul li:hover .dropdowncontent
, the dropdown menu does not show up at all.

In the HTML, if I put the dropdown content in the li, the next two supposed to show up in the list goes outside of the box.

Thanks in advance.

Answer

You're not giving your content elements any sort of context. Right now, as your CSS is written, all of the dropdowns will be visible on hover, because you're explicitly saying to show all of them.

So basically what you need to do is put your content elements inside a li and style it's hover selector. By the way, just for the future reference, unordered list can only have li as their children, otherwise it's not valid HTML.

https://jsfiddle.net/eo0shney/

<div class="navbar">
<ul>
<li>title</li>
<li>
  main text
  <div class="dropdown-content">
    <a href="#">text</a>
    <a href="#">text</a>
    <a href="#">text</a>
  </div>
</li>
<li>
  main text
  <div class="dropdown-content">
    <a href="#">text</a>
    <a href="#">text</a>
    <a href="#">text</a>
  </div>
</li>
<li>
  main text
  <div class="dropdown-content">
    <a href="#">text</a>
    <a href="#">text</a>
    <a href="#">text</a>
  </div>
</li>