我有一个项目主题的彩色 Sass map ,让我有机会循环和生成类选项(例如 .row--primary
和 .row--secondary
等),而无需使用 Tailwind 的变量手动指定它们。它们的定义如下:
$colors: (
'primary': theme('colors.green.700'),
'secondary': theme('colors.red.500'),
);
然后使用我的 .row
部分,我可以这样做:
.row {
@each $name, $hex in $colors {
&--#{$name} {
background: $hex;
// Setting the text colour based on how dark/light the bg is.
color: set-text-color($hex);
}
}
}
这里有一个利用 Sass 亮度函数的函数,因此我可以根据背景自动显示深色或浅色文本:
@function set-text-color($color) {
@if (lightness($color) > 80) {
@return color('black');
} @else {
@return color('white');
}
}
但这会引发以下错误:错误:“lightness($color)”的参数“$color”必须是颜色
。
我已经尝试了很多方法来解决这个问题。当我将使用 tailwind 变量 (theme('colors.green.700')
) 的主题 map 变量替换为基本十六进制时,它可以工作。有什么办法可以解决这个问题,以便我仍然可以访问 TailwindCSS 变量吗?
最佳答案
Tailwind 在 PostCSS 阶段应用,该阶段位于 less、scss、sass 处理器之后。由于 theme() 是 Tailwind 函数,因此该值在预处理器编译期间不可用。
进一步解释这种特殊情况in the documentation .
我还没有尝试过(但很快就会尝试),但您应该能够将颜色值存储在 JSON 文件中。然后使用 this plugin 在 SCSS 中导入此文件。然后返回到 tailwind.config.js
中导入此 JSON 文件并使用其中的值。这将为您的值(value)观创建单一的事实来源。
关于Sass lightness() 函数不适用于 TailwindCSS 主题变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63910858/