简体   繁体   English

在变量内使用SCSS变量

[英]Using SCSS variable inside a variable

I want to use a SCSS loop as below: 我想使用一个SCSS循环,如下所示:

@each $var in dark, purple, green, cyan, silver, white {

  .text-#{$var} {
    color: nth($color-, $var);
  }
  .btn-#{$var} {
    background-color: nth($color-, $var);
  }
}

in order to use the following variables: 为了使用以下变量:

$color-dark: #0D0E1E;
$color-purple: #333366;
$color-green: #33cc99;
$color-cyan: #00cccc;
$color-silver: #ccc;
$color-white: #fff;

but it is not working. 但它不起作用。 $color-#{$var} was not working as well. $color-#{$var}不能正常工作。 Can I do this? 我可以这样做吗?

nth gets an item in a list. nth获取列表中的项目。 The first argument is the list, the 2nd is an index in the list. 第一个参数是列表,第二个参数是列表中的索引。 Also SASS thinks anything with a $ is a variable, so $color- is a variable. 同样,SASS认为带有$的任何内容都是变量,因此$ color-是变量。 You haven't defined $color- as a variable, and that's not your intended use. 您尚未将$ color-定义为变量,这不是您的预期用途。

DOCS . DOCS

But you can get your desired result with a map... 但是您可以通过地图获得想要的结果...

DEMO DEMO

$color-dark: #0D0E1E;
$color-purple: #333366;
$color-green: #33cc99;
$color-cyan: #00cccc;
$color-silver: #ccc;
$color-white: #fff;

$colors: (
  dark: $color-dark,
  purple: $color-purple,
  green: $color-green,
  cyan: $color-cyan,
  silver: $color-silver,
  white: $color-white
);

@each $name, $val in $colors {
  .text-#{$name} {
    color: $val;
  }

  .btn-#{$name} {
    background-color: $val;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM