在可滚动容器中将 flex 父级拉伸到(可变)子级宽度

Stretch flex parent to (variable) children width in scrollable container

这是我的(从外到内):

  1. 具有 overflow: scroll 和固定宽度的父元素。
  2. 宽度可变的垂直元素列表
  3. 列表项有 display: flexflex-direction: row
  4. 在每个列表项中,都有一个图标和一个水平并排的标签

我希望列表项的宽度与容纳其 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>