Sass n子嵌套

CSS

阳光乐

2020-03-24

我将这些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)

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

第3543篇《Sass n子嵌套》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
LGO西里 2020.03.24

我会在这里变得聪明一点时要小心。我认为它确实令人困惑,使用更高级的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;
        }
      }
    }
  }
}
卡卡西 2020.03.24

你现在要做的&(2), &(4),这将无法正常工作

#romtest {
  .detailed {
    th {
      &:nth-child(2) {//your styles here}
      &:nth-child(4) {//your styles here}
      &:nth-child(6) {//your styles here}
      }
  }
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android