CSS Flex-flow:列包装。如何设置容器的宽度等于内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31135650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 11:19:49  来源:igfitidea点击:

Flex-flow: column wrap. How to set container's width equal to content?

cssflexbox

提问by korsun

I have a container and several inner divs.

我有一个容器和几个内部 div。

.container {
 display: inline-flex;
 flex-flow: column wrap;
 max-height: 500px;
}
.element {
  width: 200px;
  height: 200px;
  margin: 10px;
  background: #000;
}

Now I have 3 flex columns.

现在我有 3 个 flex 列。

What I expected: Container's width becomes equal to the sum of columns' width (660px).

我所期望的:容器的宽度等于列宽的总和(660 像素)。

What I got: Container's width becomes equal to the first column's width.

我得到了什么:容器的宽度等于第一列的宽度。

The pen: http://codepen.io/korsun/pen/zGpQrZ

笔:http: //codepen.io/korsun/pen/zGpQrZ

Why? When I change flex-direction to row and max-height to max-width everything goes just as expected. Is there a way to make my container's width equal to content width?

为什么?当我将 flex-direction 更改为 row 并将 max-height 更改为 max-width 时,一切都按预期进行。有没有办法让我的容器的宽度等于内容宽度?

回答by michael.mcshinsky

  1. Your ".wrap" container is set to "inline-block". You will want the container of ".container" to be set to "block" and then a defined with to contain the blocks overall.

  2. Your ".container" is set to "inline-flex" which is then doing the same thing as ".wrap" when you add the inline element into the picture. Setting this back to "flex" should fix your problem.

  3. Your elements inside the container should typically set to "flex: [number]" and a containing width. The current with of "200" is constraining and unfortunately unresponsive. Setting a max-width of 200 will both give it the width desired plus the responsive aspect which you can control with media queries.

  1. 您的“ .wrap”容器设置为“ inline-block”。您需要将“ .container”的容器设置为“block”,然后将其定义为包含整个块。

  2. 您的“ .container”设置为“ inline-flex”,当您将内联元素添加到图片中时,它会做与“ .wrap”相同的事情。将此设置回“ flex”应该可以解决您的问题。

  3. 容器内的元素通常应设置为“ flex: [number]”和包含宽度。当前的 "200" 是约束性的,不幸的是没有响应。将 max-width 设置为 200 既可以提供所需的宽度,又可以提供可以通过媒体查询控制的响应方面。

http://codepen.io/mmcshinsky/pen/bd927e31d2df2f9180a5b7fcf1df2740/

http://codepen.io/mmcshinsky/pen/bd927e31d2df2f9180a5b7fcf1df2740/

.wrap {
  display: block;
  max-width: 660px;
}
.container {
  display: flex;
  flex-flow: column wrap;
  max-height: 500px;
}

.element {
  max-width: 200px;
  height: 200px;
  margin: 10px;
  background: #000;
  flex: 1;
}