This question already has an answer here:
Make flex items take content width, not width of parent container
(1个答案)
两年前关闭。
我试着根据内容来设置每个项目的宽度,但是到目前为止我已经将宽度设置为可用空间。flex:0 0 auto似乎不起作用。我做错什么了?
目标是根据内容大小设置宽度。
[Hello]
[Hello world]

目前
[Hello                   ]
[Hello world             ]

https://jsfiddle.net/v6cgLjbd/8/
<span class='box'>
  <span class='item'>Hello</span>
  <span class='item'>Hello World</span>
  <span class='item'>Hello lOOOOONG text</span>
</span>

.box {
  height: 200px;
  width: auto;
  border: 1px solid red;
  display: flex;
  flex-direction: column;
}

.item {
  background-color: gray;
  flex: 0 0 auto;
  width: auto;
}

最佳答案

您需要在flex容器上添加align-items: flex-start。在父元素上使用flex-direction: column时,在子元素上使用flex属性可以控制高度而不是宽度。

.box {
  height: 200px;
  border: 1px solid red;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.item {
  background-color: gray;
}

<span class='box'>
  <span class='item'>Hello</span>
  <span class='item'>Hello World</span>
  <span class='item'>Hello lOOOOONG text</span>
</span>

10-05 20:44
查看更多