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

CSS实现不等尺寸元素桌面1-2/3-4布局、移动端堆叠的间隙问题求解

你遇到的float布局间隙问题根源是:左列第一个元素test1高度远高于右列第一个元素test2,左浮动的test3会紧随test1下方排列,此时右列上半部分空间被test1的高度占用,右浮动的test4只能在test1高度结束的位置开始排列,自然就和test2之间出现了大段空白。

最优解决方案:使用CSS Grid实现

无需修改现有HTML结构,代码更简洁,也不存在浮动带来的高度差间隙问题,完全符合你需要的布局效果:

.test1 {
  background: red;
}

.test2 {
  background: yellow;
}

.test3 {
  background: lightblue;
}

.test4 {
  background: green;
}

.wrap {
  display: grid;
  /* 左列占2/3宽度,右列占1/3宽度,gap属性可调整元素间距,0代表无间距 */
  grid-template-columns: 2fr 1fr;
  gap: 0;
}

@media(max-width: 992px) {
  .wrap {
    /* 移动端改为单列,自动垂直堆叠 */
    grid-template-columns: 1fr;
  }
}

footer {
  clear: both;
}

直接替换掉你原有CSS中section:nth-child相关的浮动、宽度代码即可使用。

兼容旧浏览器的float改造方案

如果需要兼容不支持Grid的旧浏览器,可以调整HTML结构,把左右列拆分单独包裹,也能消除间隙:

<div class="wrap">
  <div class="left-col">
    <section class="test1">原有内容</section>
    <section class="test3">原有内容</section>
  </div>
  <div class="right-col">
    <section class="test2">原有内容</section>
    <section class="test4">原有内容</section>
  </div>
</div>

对应新增CSS:

.left-col {
  float: left;
  width: 66%;
}
.right-col {
  float: right;
  width: 33%;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:18:03