使用SASS列表项作为变量名

时间:2017-01-26 16:37:32

标签: sass

我目前正在尝试遍历SASS列表并使用其中的项目来匹配我的代码中的变量名称,以便我可以在循环内使用这些变量,同时还使用列表字符串来创建类。

目前我得到的是......

$sections: upcoming messages profile area report;

@each $section in $sections {
    .#{$section} {
        h2 { color: $#{$section};   }
        h2:after { background-color: $#{$section}; }
    }
}

我的假设是我无法使用" $ section"在"#{}"内但如果是这样的话,那么实现我想做的事情的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

以下解决方案适用于Sass 3.3

//make sure the color variables are defined before calling the @each function
$upcoming: green;
$messages: yellow;
$profile: red;
$area: blue;
$report: black;


$sections: (upcoming: $upcoming, messages: $messages, profile: $profile, area: $area, report: $report);

@each $section, $color in $sections {
   .#{$section} {
      h2 { color: $color }
      h2:after { background-color: $color }
    }
}

您将获得以下css:

.upcoming h2 {
   color: green;
}

.upcoming h2:after {
   background-color: green;
}

.messages h2 {
   color: yellow;
}

.messages h2:after {
  background-color: yellow;
}
...
相关问题