css - 使用 mixin 参数作为变量

标签 css sass scss-mixins

所以我有不同的变量,并希望根据我给出的参数(这也是一个变量)生成 css。

我想使用给定的参数作为变量名。 F.e.当给定 primary 作为参数时,我实际上想获得变量 $primary-brighter 的值。

例如:

$primary: #f5f5f5;
$primary-brighter: #fff;

$secondary: #000;
$secondary-brighter: #333;

混合:

@mixin button-style($argument) {

 background: $argument
 color: $argument-brighter
}

正在使用中:

.button-primary {
 @include button-style(primary)
}

我期望得到的:

.button-primary {
 background: #f5f5f5;
 color: #fff
}

我得到的:

Error or
.button-primary {
 background: primary-brighter
}

我需要转义参数才能将其用作变量吗? ? 还是我的方法完全错误?

最佳答案

不确定是否有更简洁的方法,但您可以使用 maps 实现类似的效果.一种方法是将您的按钮类定义为一个 map 的键,该 map 包含要使用的实际颜色的另一个 map :

$button-colors: (

  "primary": (
    background: #f5f5f5,
    color: #fff
  ),

  "secondary": (
    background: #000,
    color: #333
  )

);

然后在您的混合中,您的 $argument 将是一个文本值而不是十六进制值,您可以访问按钮颜色图:

@mixin button-style($argument) {

  $color-map: map-get($button-colors, $argument);

  background: map-get($color-map, background);
  color: map-get($color-map, color);

}

mixin 然后会像这样被消耗:

.button-primary {
 @include button-style(primary)
}

.button-secondary {
 @include button-style(secondary)
}

关于css - 使用 mixin 参数作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58028921/

相关文章:

css - 如何从 scss mixin 更改另一个变量中使用的变量值

css - 为什么不为 Compass/Blueprint Grid 使用语义类名?

css - 将 Superfish 集成到 Wordpress 中

html - 如何将一个新的 div 放在另一个 div 下以创建一个新的部分?

jquery - Tiny carousel 的 "#Next"和 "#Prev"函数在 mvc 元素中不起作用

sass - 带插值变量的数学?

html - 使用 SCSS 的背景图像不起作用 - `webpackMissingModule` 错误

css - 更改 :root CSS RGB Variables 的不透明度

css - 如何在 SCSS 中使用多个 @include?

html - 标题图像始终位于屏幕中间