HTML dropdown menu has many <li menu items which causes it to wrap

Viewed 47

The problem lies when adding to many menu items to fit on one line, it doesn't warp left to right on the second line in the menu. The result I'm looking for is for as the menu grows, the second line in the menu will start on the left as the first menu line does. Any help would be awesome. Note: We are not using any JS in this solution.

li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  /* White color */
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}
<li style="float:left" class="dropdown"> <a href="javascript:void(0)" class="dropbtn">MENU ITEM # 1</a>
  <div class="dropdown-content"> <a href="" target="_blank" title="This is the test.">  &nbsp; menu item</a> </div>
</li>

Thanks

1 Answers

Add the following CSS:

#menu > ul { 
    white-space: nowrap;
}

#menu > ul > li {
  display: inline-block;
  float: none;
  margin: 0 -3px 0 0;
}

float: none is needed to override the rule #menu li { float: left; }, which causes the parent ul's white-space: nowrap rule to be ignored.

display: inline-block produces an inline layout for the list items, but still allows them to be treated like block elements with respect to sizing and positioning.

The negative margin-right is needed to override the default conversion of a line break in the HTML source to a single space; without it, your top-level menu items will have spaces between them.

Related