2013-12-10 16 views
13

sto refactoring questi selettori CSS verso Sass:Sass nth-child nidificazione

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

... e si avvicinò con questo:

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

Purtroppo questo sta gettando un errore:

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

so anche questo potrebbe essere meglio perché sono:

  • ripetendo il colore di sfondo
  • ripetendo i numeri - vale a dire (2) e (6)

Come devo refactoring questi selettori?

risposta

24

Farei attenzione a cercare di diventare troppo intelligente qui. Penso che sia confuso com'è e usare i parametri più avanzati nth-child renderà tutto più complicato. Per quanto riguarda il colore dello sfondo, l'avrei appena impostato su una variabile.

Ecco cosa mi è venuto in mente prima di rendermi conto che provare a essere troppo intelligente potrebbe essere una brutta cosa.

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

ed ecco un breve demo: http://codepen.io/anon/pen/BEImD

---- ---- EDIT

Ecco un altro approccio per evitare di digitare nuovamente 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

È Stai cercando di fare &(2), &(4) che non funzionerà

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