【问题标题】:Flexbox, add space-between in the cross-axis when flexbox container height is set to autoflexbox,当flexbox容器高度设置为auto时,在横轴上添加space-between
【发布时间】:2016-03-01 20:39:08
【问题描述】:

我想知道这是否可能。

假设我有这样的布局:

.flex-container {
  align-content: space-between;
  align-items: flex-start;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}
.flex-item {
  background: tomato;
  width: 31%;
  height: 150px;
  line-height: 150px;
  color: white;
  font-weight: bold;
  font-size: 3em;
  text-align: center;
}
<div class="flex-container">
  <div class="flex-item">1</div>
  <div class="flex-item">2</div>
  <div class="flex-item">3</div>
  <div class="flex-item">4</div>
  <div class="flex-item">5</div>
</div>

.flex-container 高度必须是自动的,因为项目是动态加载的

  1. 如何在 cross-axis 与 main-axis 相同(如果 flex-item 的宽度为 31%, 31x3 = 93%,因此间距为 3.5%。
  2. 将最后一个 flex-item 对齐方式更改为类似于 flex-start 以避免它们之间的空白。

Actual layout

Desire layout

【问题讨论】:

标签: html css flexbox


【解决方案1】:

如果你事先知道元素之间的间距大小,那么你可以将边距应用于除前三个之外的所有 flexbox 项:

.flex-item:nth-of-type(1n + 4) {
  margin-top: 3.5vw;
}

或:

.flex-item:not(:nth-of-type(-1n + 3)) {
  margin-top: 3.5vw;
}

对于第二个问题,您可以添加empty placeholder flexbox items,高度为0。这样做时,将考虑这些元素来计算布局。

Updated Example

.flex-item:empty {
    visibility: hidden;
    height: 0;
    margin: 0;
}

.flex-container {
  align-content: space-between;
  align-items: flex-start;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}
.flex-item {
  background: tomato;
  width: 31%;
  height: 150px;
  line-height: 150px;
  color: white;
  font-weight: bold;
  font-size: 3em;
  text-align: center;
}
.flex-item:not(:nth-of-type(-1n + 3)) {
  margin-top: 3.5vw;
}
.flex-item:empty {
  visibility: hidden;
  height: 0;
  margin: 0;
}
<div class="flex-container">
  <div class="flex-item">1</div>
  <div class="flex-item">2</div>
  <div class="flex-item">3</div>
  <div class="flex-item">4</div>
  <div class="flex-item">5</div>
  <div class="flex-item"></div>
  <div class="flex-item"></div>
</div>

作为Shaggy points out in the comments,您也可以将父元素设置为justify-content: flex-start,然后手动添加元素之间的间距:

Updated Example

.flex-container {
  justify-content: flex-start;
}
.flex-item:not(:nth-of-type(-1n + 3)) {
  margin-top: 3.2vw;
}
.flex-item:not(:nth-of-type(3n + 3)) {
  margin-right: 3.2vw;
}

【讨论】:

  • 当您使用margin手动设置每个项目之间的间距时,您可以通过将父级的justify-content属性设置为flex-start来解决第二个问题。
  • 谢谢@Josh Crozier 和Shaggy,“vw”是什么意思?为什么它适用于“vw”而不适用于“%”?它具有与“%”相同的属性吗?我不知道……
  • vw 单位是相对于视口的百分比。 100vw 是视口宽度的 100%,100vh 是视口高度的 100%。
  • 使用% 边距不能按预期工作@JoshCrozier
  • @Mauricio,使用calc 更准确地设置孩子的宽度,例如width:calc(33.333% - 3.5vw),或者,为了更准确,width:calc((100% / 3) - 3.5vw)
猜你喜欢
  • 2020-09-06
  • 2016-01-21
  • 2023-01-31
  • 2018-04-26
  • 1970-01-01
  • 2016-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多