Use nth-child value as a SASS variable

2019-01-16 16:57发布

问题:

Is there any way to use the nth-child value as a SASS variable ?

Examples of use :

div:nth-child(n) {
    content: '#{$n}'
}
div:nth-child(n) {
    background: rgb(#{$n}, #{$n}, #{$n});
}

回答1:

I don't think there's a way to do exactly that. But you can use @for directive to loop through a known number of elements:

$elements: 15;
@for $i from 0 to $elements {
  div:nth-child(#{$i + 1}) {
     background: rgb($i, $i, $i);
  }
}


回答2:

You could use a mixin like this:

 @mixin child($n) {
     &:nth-child(#{$n}){
           background-color:rgb($n,$n,$n);
     }
 }

 div{
     @include child(2);
    }

The compiled css looks like:

div:nth-child(2) {
   background-color: #020202;
}

See an example here