html - 在换行时移除多行 flex 元素之间的空间(间隙)

标签 html css flexbox

我正在尝试在一个具有设定高度的容器中放置多个元素。如果没有剩余空间,元素将并排进行。

思路是这样的:

我正在尝试使用 flexbox 实现这一点,这是一个设置了高度的容器,方向设置为 column 并且 flex-wrapwrap:

问题是列之间有很大的差距。

enter image description here

我尝试将 justify-contentalign-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>

codepen

最佳答案

flex 容器的初始设置是align-content: stretch

这意味着多行 flex 元素将沿交叉轴均匀分布。

要覆盖此行为,请将 align-content: flex-start 应用于容器。


当您在单行 flex 容器(即flex-wrap: nowrap)中工作时,要使用的属性沿交叉轴分配空间的是 align-itemsalign-self

当您在多行 flex 容器(即 flex-wrap: wrap)中工作时——就像在问题中– 用于沿交叉轴分布 flex 线(行/列)的属性是align-content

来自规范:

8.3. Cross-axis Alignment: the align-items and align-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 property

The align-content property aligns a flex container’s lines within the flex container when there is extra space in the cross-axis, similar to how justify-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/

相关文章:

html - 如何创建像 Apple 一样的导航栏?

css - 可变宽度的 flex 元素之间的等距分隔符

javascript - 为什么我的游戏大小取决于我如何设置 Canvas 大小

html - 我设计并编写了一个网站,但是当我放大浏览器时,它会调整大小

html - 当图像穿过一条线时反转图像的颜色?

html - 如何在html中创建颜色选择器?

html - 样式 `.h1` 类类似于 `h1` 标签

html - 我怎样才能让我的 BG 包装器一直加载到页面下方,或者显示在内容之前?

html - 仅在加载 "font-family"时显示文本

css - 使用 CSS flexbox 网格填充 API 数据