我正在尝试在一个具有设定高度的容器中放置多个元素。如果没有剩余空间,元素将并排进行。
思路是这样的:
我正在尝试使用 flexbox 实现这一点,这是一个设置了高度的容器,方向设置为 column
并且 flex-wrap
是 wrap
:
问题是列之间有很大的差距。
我尝试将 justify-content
和 align-items
都设置为 flex-start
,但这可能是默认值。
有什么办法可以解决吗?
代码如下:
* {
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
.container {
display: flex;
flex-wrap: wrap;
height: 300px;
flex-direction: column;
background-color: #ccc;
}
.items {
width: 100px;
height: 100px;
margin: 10px;
background-color: tomato;
color: white;
font-size: 60px;
font-weight: bold;
text-align: center;
padding: 15px;
}
<div class="container">
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
<div class="items">5</div>
</div>
最佳答案
flex 容器的初始设置是align-content: stretch
。
这意味着多行 flex 元素将沿交叉轴均匀分布。
要覆盖此行为,请将 align-content: flex-start
应用于容器。
当您在单行 flex 容器(即flex-wrap: nowrap
)中工作时,要使用的属性沿交叉轴分配空间的是 align-items
和 align-self
。
当您在多行 flex 容器(即 flex-wrap: wrap
)中工作时——就像在问题中– 用于沿交叉轴分布 flex 线(行/列)的属性是align-content
。
来自规范:
8.3. Cross-axis Alignment: the
align-items
andalign-self
properties
align-items
sets the default alignment for all of the flex container’s items, including anonymous flex items.align-self
allows this default alignment to be overridden for individual flex items.8.4. Packing Flex Lines: the
align-content
propertyThe
align-content
property aligns a flex container’s lines within the flex container when there is extra space in the cross-axis, similar to howjustify-content
aligns individual items within the main-axis. Note, this property has no effect on a single-line flex container.
align-content
属性有六个值:
flex 启动
flex-end
居中
空格
space-around
拉伸(stretch)
下面是 stretch
的定义:
stretch
Lines stretch to take up the remaining space. If the leftover free-space is negative, this value is identical to
flex-start
. Otherwise, the free-space is split equally between all of the lines, increasing their cross size.
换句话说,横轴上的 align-content: stretch
类似于主轴上的 flex: 1
。
关于html - 在换行时移除多行 flex 元素之间的空间(间隙),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44163077/