【问题标题】:Shrink flexbox container to content size [duplicate]将flexbox容器缩小到内容大小[重复]
【发布时间】:2017-12-16 00:23:40
【问题描述】:

如果您使用 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>

【问题讨论】:

标签: html css flexbox


【解决方案1】:

你可以使用display: inline-flex;(见Designating a Flexible Box):

.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>

【讨论】:

  • 哇,我怎么不知道inline-flex?这是标准的 flexbox 功能吗?我什至从未读过它。
  • 确实如此。这是我为什么需要这个之一,直到你这样做:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 2020-03-22
  • 2017-06-03
相关资源
最近更新 更多