Reputation: 6217
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:
How should I refactor these selectors?
Upvotes: 26
Views: 158384
Reputation: 1279
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}
}
}
}
Upvotes: 5
Reputation: 32921
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;
}
}
}
}
}
Upvotes: 46