sass 后续嵌套元素中的替代颜色

sass alternate color in subsequent nested elements

假设我想改变 div 的背景颜色,如果它嵌套在另一个具有相同类名的 div 中。

示例:

.my-div {
    background-color: white;
    .my-div {
      background-color: grey;
      .my-div {
        background-color: white;
        .my-div {
          background-color: grey;
          .my-div {
            background-color: white;
            .my-div {
              background-color: grey;
              .my-div {
                background-color: white;
                .my-div {
                  background-color: grey;
                }
              }
            }
          }
        }
      }
    }
  }

有没有办法通过 sass 循环或其他功能更简单地实现这一点,比如 8 个级别?

@mixin altBox($n) {
  $n: $n + 1;

  .alternator {
    @if $n % 2 == 0 {
      background: white;
    } @else {
      background: gray;
    }
    @if ($n < 9) {
      @include altBox($n);
    }
  }
}

@include altBox(0);

能够通过递归混合实现它