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

如何合并Flex列避免过度拉伸,解决小列空间浪费问题

问题场景

部分Flex列尺寸较大,其余列尺寸较小,希望合并这些小列以避免空间浪费。容器div的flex-direction为row,列同样是div元素,这是默认表现,请问如何修改以实现预期效果?

Flex布局空间浪费示意图

代码片段

CSS代码

#container { display: flex; flex-flow: row wrap; background: red; width: 300px; }
#container div { background: blue; width: 100px; height: 40px; }
#container div.large { background: green; height: 200px; }

HTML代码

<div id="container">
  <div>1</div>
  <div>2</div>
  <div class="large">3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</div>

解决方案

采用垂直流式Flex布局可以实现小列合并、避免空间浪费的效果,核心修改如下:

调整容器的Flex方向为垂直排列并允许换行,同时设置与大列高度匹配的最大高度,让小列自动填充大列旁的空白区域。修改后的CSS代码:

#container {
  display: flex;
  flex-flow: column wrap; /* 改为垂直方向排列并换行 */
  max-height: 200px; /* 匹配大列高度,触发换行填充空白 */
  width: 300px;
  background: red;
}
#container div {
  background: blue;
  width: 100px;
  height: 40px;
}
#container div.large {
  background: green;
  height: 200px;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 13:49:56