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

如何用Sass循环实现同class嵌套div背景色交替效果

可以通过Sass的@for循环实现,仅需少量代码即可完成最多8层的交替效果,且后续调整嵌套层数、交替颜色都非常方便。

实现代码

// 配置项:交替背景色、最大嵌套层数
$alternate-colors: white, grey;
$max-nest-level: 8;

.my-div {
  // 第一层默认用第一个颜色
  background-color: nth($alternate-colors, 1);
  // 存储当前层级的选择器
  $current-selector: &;

  // 从第二层开始循环生成嵌套样式
  @for $level from 2 through $max-nest-level {
    $current-selector: $current-selector .my-div;
    #{$current-selector} {
      // 奇数层用第一个颜色,偶数层用第二个颜色
      background-color: nth($alternate-colors, if($level % 2 == 1, 1, 2));
    }
  }
}

逻辑说明

  • 你可以直接修改$alternate-colors变量更换交替的颜色,修改$max-nest-level调整支持的最大嵌套层数,不需要改动其他逻辑。
  • 这段代码编译后输出的CSS和你手动编写的嵌套样式完全一致,不需要调整现有HTML结构,效果没有任何差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:45:03