CSS 使用 nth-child 值作为 SASS 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20120399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:05:53  来源:igfitidea点击:

Use nth-child value as a SASS variable

csssasscss-selectors

提问by zessx

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

有没有办法将该nth-child值用作 SASS 变量?

Examples of use :

使用示例:

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

回答by myajouri

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

我不认为有办法做到这一点。但是您可以使用@for指令循环遍历已知数量的元素:

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

回答by Jens Cocquyt

You could use a mixin like this:

你可以使用这样的 mixin:

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

 div{
     @include child(2);
    }

The compiled css looks like:

编译后的 css 如下所示:

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

See an example here

在此处查看示例