【问题标题】:How to vertically wrap content with flexbox?如何使用 flexbox 垂直包装内容?
【发布时间】:2016-09-21 20:49:51
【问题描述】:

我在一个 flexbox 容器内有三个 div。

我希望三个divs 显示如下:

+-----------------------------------------------+
|     +-----------------+-----------------+     |
|     |                 |                 |     |
|     |                 |                 |     |
|     +-----------------+-----------------+     |
|                                               |
|     +-----------------------------------+     |
|     |                                   |     |
|     |                                   |     |
|     +-----------------------------------+     |
|                                               |
+-----------------------------------------------+

因此容器必须垂直适应其内容,但仅适应其内容,仅此而已。

不过,我在 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% 高度?

提前致谢!

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    创建弹性容器时,初始设置为align-content: stretch

    这会导致多行弹性项目在容器的整个长度上分布。

    #container 上用align-content: flex-start 覆盖此设置。


    要使#container 垂直收缩其内容,您需要删除此规则:

    #container { bottom: 0; }
    

    因为#container是绝对定位的,并且没有定位的父元素,会为#container建立包含块,所以默认包含块成为初始包含块 或者,视口。

    这就是容器从上到下延伸的原因,如您应用的黑色边框所示。删除 bottom: 0 后,容器的行为将更像 height: auto

    在此处了解有关 CSS 定位的更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/position

    【讨论】:

    • 谢谢!它非常接近,但不完全是我想要的。它仍然没有使容器的高度适应其内容。只需将内容放在一起(两种方法之一)。看here.
    • 我有bottom: 0 因为我想让容器在屏幕上垂直和水平居中。我想我现在必须找到另一种方法来居中。
    • 要使容器在屏幕上居中,只需使用另一个弹性容器:jsfiddle.net/rf15p2vw/2
    • 谢谢!抱歉回复太晚了。我考虑过,但我也怀疑在body 标签上放置flex 是否是个好主意。现在你澄清我的想法。再次感谢你:)
    • 当然。你是我最好的帮手之一:)
    猜你喜欢
    • 1970-01-01
    • 2019-05-13
    • 2017-03-21
    • 2020-11-04
    • 2021-11-06
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 2013-10-04
    相关资源
    最近更新 更多