我需要正确地为菜单/树状结构设置皮肤。
每个项目由三个元素组成:两个浮动(一个左浮动和一个右浮动),最后一个非浮动填充剩余空间,在可能的情况下自动扩展容器。
在第一级中,所有渲染都正确,但在子级别上,容器的宽度太小。
注意:我需要每个级别ul
容器根据其内容独立调整大小。
HTML示例结构:
<ul>
<li>
<div class="link">
<span></span>
<span>3434</span>
<span>Item 1</span>
</div>
<ul>
<li>
<div class="link">
<span></span>
<span>123</span>
<span>Item 1.2</span>
</div>
</li>
<li>
<div class="link">
<span></span>
<span>312</span>
<span>Item 1.2342342</span>
</div>
</li>
<li>
<div class="link">
<span></span>
<span>12</span>
<span>Item 1.2234123</span>
</div>
</li>
</ul>
</li>
<li>
<div class="link">
<span></span>
<span>3453</span>
<span>Item 2123123123123123123</span>
</div>
</li>
<li>
<div class="link">
<span></span>
<span>34534</span>
<span>Item asdasdasd</span>
</div>
</li>
</ul>
CSS:
ul {
position: absolute;
background: white;
border: 1px solid black;
overflow: visible;
margin: 0;
padding: 0;
}
li {
position: relative;
margin: 0;
padding: 0.1em 0.5em;
}
ul>li>ul {
left: 100%;
}
.link {
display;
block;
position: relative;
}
.link>span:nth-child(1) {
display: block;
float: left;
width: 1em;
height: 1em;
margin-right: 0.25em;
background: cyan;
}
.link>span:nth-child(2) {
display: block;
float: right;
height: 1em;
margin-left: 0.25em;
background: red;
color: white;
}
.link>span:nth-child(3) {
display: block;
white-space: nowrap;
overflow: auto;
}
答案 0 :(得分:1)
您可以增加.ul>.li>.ul
元素的宽度:
ul>li>ul {
left: 100%;
width:100%;
}
这将使其增加到与顶级菜单相同的宽度:
答案 1 :(得分:0)
您可以将内部<ul>
渲染为一个表格,它会自动调整大小以适应其内容:
ul>li>ul {
left: 100%;
display: table;
}
答案 2 :(得分:0)
最后我找到了使用flexbox模型的解决方案。此方法还保留了jQuery动画。
只需要更新CSS:
ul {
display: block;
position: absolute;
list-style: none;
background-color: orange;
border: 1px solid red;
padding: 0.2em;
}
li {
display: block;
}
ul>li>ul {
left: 100%;
}
.link {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: flex-start;
align-items: stretch;
align-content: stretch;
margin: 0.2em;
}
.link>span {
display: block;
align-self: auto;
}
.link>:nth-child(1) {
flex-shrink: 0;
width: 1em;
background-color: cyan;
margin-right: 0.25em;
}
.link>:nth-child(2) {
order: 1;
flex-shrink: 0;
background-color: red;
margin-left: 0.25em;
white-space: nowrap;
color: white;
}
.link>:nth-child(3) {
flex-basis: 100%;
flex-shrink: 1;
background-color: yellow;
white-space: nowrap;
}
此处更新了jsfiddle。