2

I have a ul navigation menu with equidistant inline-block elements that each have a submenu.

The problem is I can't get the submenu's width to adjust to the length of the child elements. It's inheriting the width of the parent.

I could set a fixed width but since each of my submenus has different links with varying length, I would ideally like to have each submenu to have an auto width and fit nicely with it's content.

Apologies for the long code script. You can see a JSFiddle here which will probably better explain the problem:

http://jsfiddle.net/sbd81hco/

HTML

<nav>
    <ul>
        <li><a href="">Section A</a><ul>
                <li><a href="">Longer Child Text</a></li>
                <li><a href="">Longer Child Text</a></li>
                <li><a href="">Longer Child Text</a></li>
            </ul>
        </li>
        <li><a href="">Section B</a>
             <ul>
                <li><a href="">Longer Child Text</a> </li>
                <li><a href="">Longer Child Text</a></li>
                <li><a href="">Longer Child Text</a></li>
            </ul>
        </li>
    </ul>
</nav>

CSS

nav > ul {
    display: inline-block;
    text-align: justify;
}

nav > ul > li {
    display: inline-block;
    position: relative;
}

nav > ul > li > ul {
    display: none;
    position: absolute;
    top: 40px;
    left: 0;
}

nav > ul > li > ul > li > a {
    width: 100%;
    height: 100%;
    display: block;
}

nav > ul > li > ul:before {
    content:' ';
    width: 100%;
    height: 40px;
    position: absolute;
    top: -40px;
    left: 0;
}

nav > ul > li:hover > ul {
    display: inline-block;
}

nav > ul:after {
    content:' ';
    display: inline-block;
    width: 100%;
    height: 41px;
}
Juicy
  • 11,840
  • 35
  • 123
  • 212

1 Answers1

5

One common approach is to add white-space: nowrap to the desired elements. In doing so, the element's width will expand to fit its contents.

Example Here

nav > ul > li > ul {
    display: none;
    text-align: left;
    position: absolute;
    top: 40px;
    left: 0;
    padding: 10px;
    background-color: #bfe17e;
    white-space: nowrap;
}

In addition, you could also set a max-width for the elements along with text-overflow: ellipsis in order to prevent the element from taking up too much horizontal space. Something like this would work:

Example Here

nav > ul > li > ul > li > a {
    max-width: 150px;
    text-overflow: ellipsis;
    overflow: hidden;
}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304