这是我所拥有的(从外到内):
- 父元素
overflow: scroll
和固定宽度。 - 可变宽度的垂直元素列表
- 列表项有
display: flex
和flex-direction: row
- 在每个列表项中都有一个图标和一个水平并排的标签
我希望列表项的宽度与容纳其 flexed 子项所需的一样多,因为根父项是可滚动的。我可以使用 flex-shrink: 0
使图标和标签具有所需的宽度。 .
问题是:列表项(上面列表中的#3)的宽度限制为可滚动父容器的宽度,而不是它们的子容器的宽度。
这很糟糕,因为列表项有填充和彩色背景。 <强> Here is an example on CodePen 强>。水平滚动显示“Lorem ipsum”的位置以了解我的意思。
谢谢!
最佳答案
只需将 list
设为 inline-block
元素,它就不会受到其父级宽度的限制,并且会展开以适应最长的元素:
.nav {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 200px;
background: #f1f1f5;
overflow: scroll;
}
.list {
display:inline-block;
}
.item-container {
padding: 0 16px;
background: #222225;
color: #e1e1e8;
}
.item {
display: flex;
flex-direction: row;
align-items: center;
}
.icon {
flex-shrink: 0;
}
.label {
flex-shrink: 0;
white-space: nowrap;
}
<div class="nav">
<div class="list">
<div class="item-container">
<div class="item">
<div class="icon">🎄</div>
<div class="label">Lorem ipsum dolor sit amet yata yata yata</div>
</div>
</div>
<div class="item-container">
<div class="item">
<div class="icon">🎄</div>
<div class="label">Lorem ipsum</div>
</div>
</div>
</div>
</div>
关于css - 在可滚动容器中将 flex 父级拉伸(stretch)到(可变)子级宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53895573/