SASS 函数变暗和变亮在使用颜色对象时不起作用

标签 sass

我正在尝试使用 darken sass 函数,但是当我从我的 scss 模块中的 sass 对象读取时,它认为颜色实际上是一个字符串,因此该函数无法解析传递的变量中。

变量.scss

$primary: #ae9fec;
$secondary: #d19ac1;

$theme: (
    "primary": ($primary, white),
    "secondary": ($secondary, white)
);

Button.module.scss

@each $colorGroup in $theme {
    &[data-variant="#{nth($colorGroup, 1)}"] {
        background-color: #{nth(nth($colorGroup, 2), 1)}); // this works

        &:hover {
            background-color: darken(#{nth(nth($colorGroup, 2), 1)}), 10%); // this does not because it thinks its a string.  I tried unquote() but that didn't work, still thinks it's a string.
        }
    }
}

最佳答案

如果您删除选择器规则中的插值(而不是选择器本身),它应该按预期进行编译。

这是一个测试 - 我假设您将 @each 循环嵌套在选择器中或使用 @at-root,因为基本级规则不能包含像这样的 & 字符 - 为您的规则集使用 .button 选择器:

/* variables.scss */
$primary: #ae9fec;
$secondary: #d19ac1;

$theme: (
    "primary": ($primary, white),
    "secondary": ($secondary, white)
);

/* Button.module.scss */
.button {
    @each $colorGroup in $theme {
        &[data-variant="#{nth($colorGroup, 1)}"] {
            background-color: nth(nth($colorGroup, 2), 1);

            &:hover {
                background-color: darken(nth(nth($colorGroup, 2), 1), 10%);
            }
        }
    }
}

编译后的代码如下所示:

.button[data-variant="primary"] {
  background-color: #ae9fec;
}

.button[data-variant="primary"]:hover {
  background-color: #8a74e4; /* Darkened $primary */
}

.button[data-variant="secondary"] {
  background-color: #d19ac1;
}

.button[data-variant="secondary"]:hover {
  background-color: #c177ab; /* Darkened $secondary */
}

我还删除了示例中多余的括号。

关于SASS 函数变暗和变亮在使用颜色对象时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58490138/

相关文章:

css - 如何在没有媒体查询的情况下将具有多个捕捉点的 SASS 编译为特定于屏幕尺寸的 CSS

html - 如何使该网站适合所有屏幕尺寸?

css - Rails 邮件样式

css - Sublime Text 创建 SASS - Autoprefixer - CSS 链保存时无需 Grunt

sass - 没有 CSS 源图

迁移 TypeScript 后,由 SASS 编译的 CSS 文件不会加载到 CRA 应用程序中

css - 使用 sass/css 交换颜色和背景颜色

ruby-on-rails - Ruby 哈希可以包含在 Sass 和 CoffeeScript 中,从而允许共享数据吗?

Node.js - express - Jade - 编译 SASS/LESS

css - 悬停不会改变我的 svg 的颜色