Flexbox,当flexbox容器高度设置为auto时,在横轴上添加空格

时间:2015-11-27 15:48:13

标签: html css flexbox

我试图弄清楚这是否可行。

假设我有这样的布局:



.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>
&#13;
&#13;
&#13;

.flex-container height必须为auto,因为项目是动态加载的

  1. 我如何在中间的flex-item之间完成该空间 横轴与主轴相同(如果flex-item的宽度为31%, 31x3 = 93%因此空间介于3.5%之间。
  2. 将上一个flex-item对齐方式更改为flex-start,以避免白色空间。
  3. Actual layout

    Desire layout

1 个答案:

答案 0 :(得分: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;
}