html - 如何用 flexbox 垂直包装内容?

标签 html css flexbox

我在一个 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/

相关文章:

javascript - 我的 jQuery 代码不适用于 WebStorm,但它适用于 CodePen

javascript - 如何以编程方式在 iOS 中聚焦来自 select 标签的受信任 onchange 事件的文本输入?

html - 如何显示 Font Awesome 图标

php - 我怎样才能使用这个 php 空函数来正确显示 CSS?

html - CSS:表格列中的标签

javascript - 父样式未应用于子样式属性

html - 图像不显示在 Node 元素的浏览器中

vue.js - Primevue Grid 和 Flex 布局无法正确呈现

html - 使用 calc(100% - x) 会破坏 flex 布局

html - 元素之间的 flex 空间