【问题标题】:Flex items create space between them when they wrap [duplicate]Flex项目在包装时会在它们之间创建空间[重复]
【发布时间】:2016-09-01 22:46:05
【问题描述】:

我正在尝试在具有 display: flex 的容器内添加一些元素。

问题在于,当我将屏幕缩小时,它会在我未设置的元素之间产生间隙(或者至少我不这么认为)。

我创建了一个JSFiddle 来代表我的问题。

如您所见,当您缩小屏幕时,第一个和第二个 div 之间有一个蓝色空间。

我该如何解决?

提前致谢!

html,
body {
  width: 100%;
  height: 100%;
}
#container {
  display: flex;
  height: 100%;
  background-color: blue;
}
.block {
  flex: 1;
}
#left {
  background-color: green;
}
#center {
  display: flex;
  flex: 1;
  flex-wrap: wrap;
}
#right {
  background-color: orange;
}
.flexContainer {
  flex: 1;
  width: 50%;
  min-width: 100px;
  max-width: 50%;
  height: 150px;
  background-color: red;
  padding: 10px;
}
.flexDiv {
  width: 100%;
  height: 100%;
  background-color: yellow;
}
<div id="container">
  <div id="left" class="block">Left</div>
  <div id="center" class="block">
    <div class="flexContainer">
      <div class="flexDiv"></div>
    </div>
    <div class="flexContainer">
      <div class="flexDiv"></div>
    </div>
  </div>
  <div id="right" class="block">Right</div>
</div>

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    创建弹性容器时,初始设置为align-content: stretch

    这会导致多行弹性项目沿容器的横轴均匀分布。这有点像沿主轴设置flex: 1:弹性项目均匀分布在直线上。

    因此,align-content: stretch 可能会在 flex 项目换行时造成间隙。

    简单的解决方案是用align-content: flex-start 覆盖此设置。

    revised fiddle

    html,
    body {
      width: 100%;
      height: 100%;
    }
    #container {
      display: flex;
      height: 100%;
      background-color: blue;
    }
    .block {
      flex: 1;
    }
    #left {
      background-color: green;
    }
    #center {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      align-content: flex-start; /* NEW */
    }
    #right {
      background-color: orange;
    }
    .flexContainer {
      flex: 1;
      width: 50%;
      min-width: 100px;
      max-width: 50%;
      height: 150px;
      background-color: red;
      padding: 10px;
    }
    .flexDiv {
      width: 100%;
      height: 100%;
      background-color: yellow;
    }
    <div id="container">
      <div id="left" class="block">Left</div>
      <div id="center" class="block">
        <div class="flexContainer">
          <div class="flexDiv"></div>
        </div>
        <div class="flexContainer">
          <div class="flexDiv"></div>
        </div>
      </div>
      <div id="right" class="block">Right</div>
    </div>

    参考:

    8.4. Packing Flex Lines: the align-content property

    align-content 属性对齐 flex 容器的行 当横轴有额外空间时的 flex 容器, 类似于 justify-content 在 主轴。注意,这个属性对单行 flex 没有影响 容器。

    该属性接受六个值。 stretch 是默认值。

    stretch

    线条伸展以占据剩余空间。如果剩余可用空间为负,则此值与flex-start 相同。否则,空闲空间将在所有行之间平均分配,从而增加它们的交叉大小。

    剩余的值为:flex-start/flex-end/center/space-between/space-around

    【讨论】:

      猜你喜欢
      • 2021-11-13
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 2012-11-14
      • 2020-10-16
      • 1970-01-01
      • 2021-07-05
      • 2019-06-24
      相关资源
      最近更新 更多