Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass nth-child nesting

Tags:

I'm refactoring these CSS selectors over to 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; } 

...and came up with this:

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

Unfortunately this is throwing an error:

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

I also know this could be better because I'm:

  • repeating the background color
  • repeating numbers - i.e. (2) and (6)

How should I refactor these selectors?

like image 751
Ryan Avatar asked Dec 10 '13 16:12

Ryan


2 Answers

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

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

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping 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;         }       }     }   } } 
like image 67
Bill Criswell Avatar answered Oct 31 '22 02:10

Bill Criswell


You're trying to do &(2), &(4) which won't work

#romtest {   .detailed {     th {       &:nth-child(2) {//your styles here}       &:nth-child(4) {//your styles here}       &:nth-child(6) {//your styles here}       }   } } 
like image 38
Vinay Raghu Avatar answered Oct 31 '22 02:10

Vinay Raghu