【问题标题】:Replace a variable and scope the result with sass [duplicate]用 sass 替换变量并确定结果范围 [重复]
【发布时间】:2015-07-08 02:34:29
【问题描述】:

我正在尝试使用 sass 找到一个智能解决方案,用于替换品牌颜色变量并为我拥有的每个组件确定结果范围。

例如这是我的.scss

$value-to-replace: #000000;
$brand-color-1:    #007be4;
$brand-color-2:    #e1a22e;

.btn {
  margin: 0;
  padding: 10px;
  background-color: $value-to-replace;
}

这是我正在尝试生成的已编译的.css

.btn {
  margin: 0;
  padding: 10px;
}
.brand-color-1 > .btn{
  background-color: #007be4;
}
.brand-color-2 > .btn{
  background-color: #e1a22e;
}

为了写这个.html

<main class="brand-color-1">
  <a class="btn" href="#">Button Text</a>
</main>

<main class="brand-color-2">
  <a class="btn" href="#">Button Text</a>
</main>

我想要实现的是允许我在所有组件中使用变量$value-to-replace。无需为每个组件编写mixin

有什么想法吗?感谢您的帮助!

【问题讨论】:

标签: css sass mixins scoping


【解决方案1】:

您可以使用 Sass 列表(以及 nth function)和 @while 循环:

$colors: (#007be4, #e1a22e);

.btn {
  margin: 0;
  padding: 10px;
}

$index: 1;

@while $index <  3
{
  .brand-color-#{$index} > .btn { 
     background-color: nth($colors, $index);
  }
  $index: $index + 1;
}

对于列表中的每种颜色,您将为该值创建一个新类。 Sass 列表不是从零开始的。

不过,这并不能解决使用单个变量的问题。它只是解决了多个mixin的问题。

编辑: JSBin of code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 2019-01-09
    相关资源
    最近更新 更多