将flexbox容器缩小到内容大小 [英] Shrink flexbox container to content size

查看:188
本文介绍了将flexbox容器缩小到内容大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您使用Flexbox布局来连续布置某些项目,则Flexbox容器将占用其所在容器的全部宽度。如何设置Flexbox容器使其仅占据其子元素的宽度?

If you are using a Flexbox layout to layout some items in a row, the Flexbox container takes up the full width of whatever container it is in. How do you set the Flexbox container to only take up the width of it's child elements?

看看下面的示例:

https://jsfiddle.net/5fr2ay9q/

在此示例中,flexbox容器的大小扩展了超出子元素的宽度。修复此类问题的典型方法是 display:inline ,但显然这行不通,因为那时它已不再是flexbox容器。

In this example the size of the flexbox container extends beyond the child element's width. The typical way to fix something like this is display: inline but obviously that won't work because then it's not a flexbox container anymore.

是否可以这样做?

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

推荐答案

您可以使用 display:inline-flex; (请参阅指定柔性盒):

You can use display: inline-flex; (see 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>

这篇关于将flexbox容器缩小到内容大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆