我有一个导航栏,其中每个列表项的字符长都相差很大。我更喜欢在auto上保留宽度并添加填充以为每个项目定义相同宽度的视觉效果。
我希望下拉菜单继承其父级列表元素的宽度。相反,它们与自己的内容一样广泛。
手动定义每个下拉菜单的宽度似乎是一个非常微妙的解决方案,尽管我已经尝试过了。它也不是特别敏感。
我还尝试将ul li ul width设置为继承,但无济于事。
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;
}
相对于手动定义每个下拉列表的宽度,是否有更好的解决方案来将下拉列表设置为其父列表项的宽度?
答案 0 :(得分:0)
这是代码
#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: 100%;
display: inline-table;
}
ul li ul li {
background-color: #181818;
margin-left: -7em;
display: none;
width: 100%;
}
ul li:hover ul li {
display: block;
}
<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>
width: 100%;
和display: inline-table;
是真实的东西
答案 1 :(得分:0)
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;
}