Javier Garcia
Javier Garcia

Reputation: 41

Submenu in a navigation bar: li's width doesn't fit the text length

I have a navigation-bar with a submenu. The problem: the li's width in the submenu doesn't fit the text length. Why?

ul {
        margin: 0;
        padding: 0;
        list-style: none;
      }
      
      #nav-bar > li {
        float: left;
        position
      }
      
      .has-submenu {
        position: relative;
      }
      .submenu {
        position: absolute;
        
      }
<ul id="nav-bar">
      <li>Item 1</li>
      <li class="has-submenu">Item 2
        <ul class="submenu">
          <li>Subitem 1</li>    
          <li>Subitem 2</li>
        </ul>
      </li>
      <li>Item 3</li>
    </ul>

Upvotes: 0

Views: 220

Answers (3)

Jushimla
Jushimla

Reputation: 1

The problem is that your .submenu > li elements width are computed from the parent element.

Setting the parent element width would fix that (ie .has-submenu).

Upvotes: 0

ZeWebDev
ZeWebDev

Reputation: 204

Because the submenu is positioned absolutely so it will only take the minimum width that it needs. As ankita patel said giving it white-space: nowrap will fix it.

Upvotes: 0

ankita patel
ankita patel

Reputation: 4251

Give white-space: nowrap; to .submenu li class.

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

#nav-bar > li {
  float: left; 
}

.has-submenu {
  position: relative;
}
.submenu {
  position: absolute;
}
.submenu li{
  white-space: nowrap;
}
<ul id="nav-bar">
  <li>Item 1</li>
  <li class="has-submenu">Item 2
    <ul class="submenu">
      <li>Subitem 1</li>    
      <li>Subitem 2</li>
    </ul>
  </li>
  <li>Item 3</li>
</ul>

Upvotes: 1

Related Questions