Search code examples
htmlcssformatdropdownresponsive

Dropdown menus breaking when parent width undefined


I've got a navigation bar where the character length of each list item varies substantially. I prefer the visual effect of leaving width on auto and adding padding to defining the same width for each item.

I want my drop downs to inherit the width of their parent list elements. Instead, they're as wide as their own content.

Manually defining the width of each drop down seems like a really inelegant solution, although I've tried it. It's also not particularly responsive.

I've also tried setting ul li ul width to inherit, to no avail.

HTML:

  <div id="nav"> <!--nestled in div to provide full view-width bar-->
    <ul>
      <li>Item 1 is medium
        <ul>
          <li><a>Section 1</a></li>
          <li><a>Section 2</a></li>
          <li><a>Section 3</a></li>
        </ul>
      </li>
      <li>Item 2 is medium
        <ul>
          <li><a>Section 1</a></li>
          <li><a>Section 2</a></li>
          <li><a>Section 3</a></li>
        </ul>
      </li>
      <li>Item 3 is very long
        <ul>
          <li><a>Section 1</a></li>
          <li><a>Section 2</a></li>
          <li><a>Section 3</a></li>
        </ul>
      </li>
      <li>Item 4 is short
        <ul>
          <li><a>Section 1</a></li>
          <li><a>Section 2</a></li>
          <li><a>Section 3</a></li>
        </ul>
      </li>
    </ul>
  </div>

CSS:

#nav {
  background-color: #181818;
  width: 100vw;
}

ul {
  height: 60px;
  margin-left: 7em;
  margin-top: 0;
  padding: 0;
  list-style: none;
  font-family: 'Open Sans', sans-serif;
}

ul li {
  float: left;
  line-height: 60px;
  text-align: center;
  color: #dcdcdc;
  padding-left: 1em;
  padding-right: 1em;
}

ul li a {
  text-decoration: none;
}

ul li ul {
  width: inherit;
}

ul li ul li {
  background-color: #181818;
  margin-left: -7em;
  display: none;
}

ul li:hover ul li {
  display: block;
}

Is there a better solution for setting the drop-downs to the width of their parent list items than manually defining the width of each drop-down?


Solution

  • CSS:

    #nav {
      background-color: #181818;
      width: 100vw;
    }
    
    #nav ul {
        padding: 0;
        list-style: none;
    }
    
    #nav > ul {
      height: 60px;
      margin-left: 7em;
      font-family: 'Open Sans', sans-serif;
    }
    
    #nav > ul > li {
      float: left;
      line-height: 60px;
      text-align: center;
      color: #dcdcdc;
      padding-left: 1em;
      padding-right: 1em;
    }
    
    
    #nav > ul li a {
      text-decoration: none;
    }
    
    #nav > ul > li > ul {
        margin-left: -1em;
        margin-right: -1em;
         display: none;
    }
    
    #nav > ul > li > ul > li {
      background-color: #181818;
    }
    
    #nav > ul > li:hover > ul {
      display: block;
    }