Dropdown Menus with Auto List-Item Widths

2019-08-06 11:51发布

So I'm working on a drop menu and I'd like each menu item to have an auto width. i.e. the background to expand to the width of the menu item rather than having an overall fixed width for all the UL. I thought that giving the ul li an auto width would sort it but it seems not. What am I missing?

<ul id="nav">
<li><a class="last" href="#">MENU &#9660;</a>
    <ul>
        <li><a href="#">Short</a></li>
        <li><a href="#">Very Long</a></li>
    </ul>
</li>

#nav { 
height: 1; 
list-style-type: none; 
padding-top: 1.25em; 
margin-top: 0em;
}

#nav li { 
float: right; 
position: relative; padding: 0;
} 

#nav li a { 
display: block; 
font-size: 14px; 
padding: 0 1em;  
margin-bottom: 1em; 
color: #333; 
text-decoration: none; 
border-left: 1px solid #333; 
}

#nav .last, #nav li ul li a {
border-left: none;
}

#nav li a:hover, #nav li a:focus {
color: #666;
}

#nav li ul { 
opacity: 0; 
position: absolute; 
right: 0em; 
list-style-type: none; 
padding: 0; margin: 0; 
}

#nav li:hover ul { 
opacity: 1; 
}

#nav li ul li { 
float: none; 
position: static; 
width: auto; 
height: 0; 
line-height: 0; 
background: none; 
text-align: right; 
margin-bottom: .75em;
}

#nav li:hover ul li { 
height: 25px; 
line-height: 2.5em;
}

#nav li ul li a { 
background: #222; 
}

#nav li ul li a:hover { 
color: #666; 
}

Mockup

2条回答
霸刀☆藐视天下
2楼-- · 2019-08-06 12:22

Your #nav li style is being applied to all child li elements, so you need to use the ">", which selects only the immediate child.

Here is updated CSS which fixes the problem. I also commented out some other CSS that was interfering:

#nav { 
    height: 1; 
    list-style-type: none; 
    padding-top: 1.25em; 
    margin-top: 0em;
}

#nav > li {  /* Added ">" */
    float: right; 
    position: relative;
    padding: 0;
} 

#nav li a { 
    display: inline-block; /* was block */ 
    font-size: 14px; 
    padding: 0 1em;  
    margin-bottom: 1em; 
    color: #333; 
    text-decoration: none; 
    border-left: 1px solid #333; 
}

#nav .last, #nav li ul li a {
    border-left: none;
}

#nav li a:hover, #nav li a:focus {
    color: #666;
}

#nav li ul { 
    opacity: 0; 
    /*position: absolute; 
    right: 0em; */
    list-style-type: none; 
    padding: 0; margin: 0; 
}

#nav li:hover ul { 
    opacity: 1; 
}

#nav li ul li { 
    /*float: none; 
    position: static; 
    width: auto;*/ 
    height: 0; 
    line-height: 0; 
    background: none; 
    text-align: right; 
    margin-bottom: .75em;
}

#nav li:hover ul li { 
    height: 25px; 
    line-height: 2.5em;
}
查看更多
做个烂人
3楼-- · 2019-08-06 12:27

You are using display: block for your links. That causes them to fill the available space. That's why they are all the same width. And float: right is contributing to the general narrowness. Use inline-block instead of block and prevent the link wrapping by using white-space: nowrap:

Demo: http://jsfiddle.net/neJty/2/

查看更多
登录 后发表回答