缩小 flexbox 容器以适应内容大小

19
如果您正在使用Flexbox布局来排列一些行中的项目,则Flexbox容器将占用其所在容器的全部宽度。如何将Flexbox容器设置为仅占用其子元素的宽度?
请看以下示例:

https://jsfiddle.net/5fr2ay9q/

在这个示例中,flexbox容器的大小超出了子元素的宽度。通常解决这种问题的方法是使用display:inline,但显然这样做不起作用,因为那样就不再是flexbox容器了。
有可能实现吗?

.container {
  display: flex;
  flex-direction: row;
  outline: 1px solid red;
}

p {
  outline: 1px solid blue;
}
Can you make the flex container not 100% width but rather the width of the content itself?

<div class='container'>
  <img src='https://placehold.it/300x300'/>
  <p>
    This is some content hello world testing 123.
  </p>
</div>


6
我不同意将问题标记为Difference between display:inline-flex and display:flex的重复。这是完全不同的问题:提问者不知道inline-flex与他们的“如何?”问题有关,除非他们在提问之前已经知道答案! - Daryn
1个回答

17
可以使用 display: inline-flex;(参见指定一个弹性盒子):

.container {
  display: inline-flex;
  flex-direction: row;
  outline: 1px solid red;
}

p {
  outline: 1px solid blue;
}
Can you make the flex container not 100% width but rather the width of the content itself?

<div class='container'>
  <img src='https://placehold.it/300x300'/>
  <p>
    This is some content hello world testing 123.
  </p>
</div>


1
哇,我怎么不知道inline-flex呢?那是标准的flexbox功能吗?我甚至从未听说过它。 - Jake Wilson
确实如此。这是“为什么我需要这个”的其中一个例子,直到你真正需要它 :) - Ori Drori

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接