我在一个 flexbox 容器中有三个 div。
我希望三个 div
显示如下:
+-----------------------------------------------+
| +-----------------+-----------------+ |
| | | | |
| | | | |
| +-----------------+-----------------+ |
| |
| +-----------------------------------+ |
| | | |
| | | |
| +-----------------------------------+ |
| |
+-----------------------------------------------+
因此容器必须垂直适应其内容,但仅限于适应其内容,仅此而已。
不过,我在 divs
之间获得了很大的空白,并且容器获得了其父级 height
的 100%。
我试过不将 height
属性放入容器并设置 height: auto;
但它们都不起作用。
这是我的代码:
*{
box-sizing: border-box;
}
html,body{
width: 100%;
margin: 0;
}
#container{
display: flex;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
justify-content: center;
align-items: center;
flex-wrap: wrap;
max-width: 450px;
border: 1px solid;
}
#div1{
width: 50%;
height: 155px;
background-color: blue;
}
#div2{
width: 50%;
height: 155px;
background-color: red;
}
#div3{
width: 70%;
height: 155px;
background-color: green;
}
<div id="container">
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
</div>
注意:将其放大以查看 div 之间的空白区域。
如何使容器收缩包装内容而不是其父级的 100% 高度?
提前致谢!
最佳答案
创建 flex 容器时,初始设置为 align-content: stretch
。
这会导致多行 flex 元素在容器的整个长度上分布。
在 #container
上使用 align-content: flex-start
覆盖此设置。
要使 #container
垂直收缩其内容,您需要删除此规则:
#container { bottom: 0; }
因为#container
是绝对定位的,没有定位的父元素,会为#container
建立包含 block ,所以默认的包含 block 变成了初始包含 block 或视口(viewport)。
这就是容器从上到下拉伸(stretch)的原因,如您应用的黑色边框所示。删除 bottom: 0
后,容器的行为将更像 height: auto
。
在此处了解有关 CSS 定位的更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/position
关于html - 如何用 flexbox 垂直包装内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37416977/