Sass nth-child nesting

问题描述 投票:16回答:2

我正在将这些CSS选择器重构为Sass:

#romtest .detailed th:nth-child(2),
#romtest .detailed th:nth-child(4),
#romtest .detailed th:nth-child(6),
#romtest .detailed td:nth-child(2),
#romtest .detailed td:nth-child(3),
#romtest .detailed td:nth-child(6),
#romtest .detailed td:nth-child(7),
#romtest .detailed td.last:nth-child(2),
#romtest .detailed td.last:nth-child(4) {
  background:#e5e5e5;
}

......想出来了:

#romtest .detailed {
    th:nth-child {
        &(2), &(4), &(6) {
            background:#e5e5e5;
        }
    }
    td:nth-child {
        &(2), &(3), &(6), &(7) {
            background:#e5e5e5;
        }
    }
    td.last:nth-child {
        &(2), &(4) {
            background:#e5e5e5;         
        }
    }
}

不幸的是,这是一个错误:

“&”之后的CSSS无效:期望“{”,是“(2),&(4),&(6){”

我也知道这可能会更好,因为我是:

  • 重复背景颜色
  • 重复数字 - 即(2)和(6)

我该如何重构这些选择器?

css sass
2个回答
29
投票

我会小心翼翼地试图在这里变得过于聪明。我认为这是令人困惑的,使用更高级的nth-child参数只会使它更复杂。至于背景颜色,我只是将它设置为一个变量。

在我意识到尝试过于聪明可能是一件坏事之前,这就是我想出的。

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

这是一个快速演示:http://codepen.io/anon/pen/BEImD

- - 编辑 - -

这是避免重新输入background-color的另一种方法:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

2
投票

你正试图做&(2), &(4)哪个不行

#romtest {
  .detailed {
    th {
      &:nth-child(2) {//your styles here}
      &:nth-child(4) {//your styles here}
      &:nth-child(6) {//your styles here}
      }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.