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

使用:nth-child实现网格中大方块交替布局的问题求助

解决CSS Grid交替跨行布局的错乱问题

当前布局期望实现右侧大盒子→左侧大盒子的无限交替循环,但现有代码导致出现了一行全是小盒子的异常行,破坏了整体节奏。

问题代码分析

原选择器规则 .child:nth-child(2), .child:nth-child(4n) 无法形成正确的交替跨行逻辑,加上固定宽度的设置干扰了Grid的自动布局计算,最终导致网格填充错乱。

修正后的CSS代码

.parent {
  margin: 0 auto;
  display: grid;
  gap: 10px;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  width: 410px;
}

.child {
  background-color: #000;
  height: 100px;
}

/* 右侧盒子跨行:第2、6、10...个元素 */
.child:nth-child(4n-2) {
  grid-row: span 2;
  height: 210px;
}

/* 左侧盒子跨行:第3、7、11...个元素 */
.child:nth-child(4n-1) {
  grid-row: span 2;
  height: 210px;
}

调整说明

  1. 移除固定宽度:删除.child的width:200px,让Grid的1fr列宽自动分配空间,避免布局计算冲突。
  2. 修正选择器逻辑:
    • 4n-2 匹配每4个元素组中的第2个,作为右侧跨行的大盒子
    • 4n-1 匹配每4个元素组中的第3个,作为左侧跨行的大盒子
      这样就能形成「小左+大右 → 大左+小右」的循环模式,彻底消除异常行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 23:30:24