2013-12-10 68 views
13

我到萨斯重构这些CSS选择器:萨斯第n个孩子筑巢

#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;   
     } 
    } 
} 

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

Invalid CSSS after "&": expected "{", was "(2), &(4), &(6) {"

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

  • 重复的背景颜色
  • 重复号码 - 即(2)和(6)

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

回答

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; 
     } 
     } 
    } 
    } 
} 
2

你'正在尝试做&(2), &(4)哪些行不通

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