You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何flex-wrap: wrap会在Flexbox交叉轴产生间隙?

Flexbox交叉轴间隙问题疑惑

我是CSS初学者,正在学习Flexbox布局。我了解flex-wrap: wrap的作用是当元素沿主轴(flex-direction: row时为水平方向)溢出时,通过换行避免溢出,但不理解为何它会在交叉轴(垂直方向)留下间隙。

我的代码

CSS代码:

#container {
  height: 300px;
  width: 80%;
  background-color: azure;
  margin: 10px auto;
  border: 2px solid black;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

h1 {
  text-align: center;
}

#container div {
  height: 90px;
  width: 300px;
  color: white;
  text-align: center;
  font-size: 1.5em;
}

HTML代码:

<h1>Flexbox Playground</h1>
<div id="container">
  <div style="background-color: #9400d3">violet</div>
  <div style="background-color: #4b0082">indigo</div>
  <div style="background-color: #0000ff">blue</div>
  <div style="background-color: #00ff00">green</div>
  <div style="background-color: #ffff00">yellow</div>
  <div style="background-color: #ff7f00">orange</div>
  <div style="background-color: #ff0000">red</div>
</div>

问题现象

最初我将子元素高度设为100px时,交叉轴未出现异常;但将高度改为50px后,垂直方向出现了间隙,这超出我的预期,我无法理解该行为的原因。

对比图

  • 子元素高度100px时:
    子元素高度100px时的布局

  • 子元素高度50px时:
    子元素高度50px时的布局

内容的提问来源于stack exchange,提问作者Sidaqpreet Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 06:53:24