根据选择器在Sass中设置变量 [英] Set a variable in Sass depending on the selector
问题描述
我有一个网站使用了几种不同的主要"颜色.常规的HTML布局保持不变,只是颜色随内容而变化.
I’ve got a website that’s using a few different ‘main’ colors. The general HTML layout stays the same, only the colors change depending on the content.
我想知道是否可以根据CSS选择器设置颜色变量.这样,我可以为我的网站设置一些变量作为主题,然后让Sass填充颜色.
I was wondering if I could set a color variable depending on the CSS selector. This way I can theme my website with a few variables and let Sass fill in the colors.
例如:
$color-1: #444;
$color-2: #555;
$color-3: #666;
$color-4: #777;
body.class-1 {
color-default: $color-1;
color-main: $color-2;
}
body.class-2 {
color-default: $color-3;
color-main: $color-4;
}
/* content CSS */
.content {
background: $color-default;
color: $color-main;
}
我当时正在考虑为此使用mixin,但是我想知道是否有更好的方法可以实现此功能?我对Sass不太满意,所以我们将不胜感激.
I was thinking of using a mixin for this, but I was wondering if there’s a better way to do this—with a function maybe? I’m not that great with Sass, so any help would be appreciated.
推荐答案
我认为在我写这篇文章时,变量将不起作用.)
I think a mixin is the answer. (As I wrote, variables won’t work.)
@mixin content($color-default, $color-main) {
background: $color-default;
color: $color-main;
}
body.class-1 {
@include content(#444, #555);
}
body.class-2 {
@include content(#666, #777);
}
SCSS 编译为此CSS:
That SCSS compiles to this CSS:
body.class-1 {
background: #444444;
color: #555555; }
body.class-2 {
background: #666666;
color: #777777; }
如果要在SCSS文件中将颜色值分组在一起,可以将变量与mixin结合使用:
If you wanted to group the color values together in your SCSS file, you could use variables in conjunction with the mixin:
$color-1: #444;
$color-2: #555;
$color-3: #666;
$color-4: #777;
body.class-1 {
@include content($color-1, $color-2);
}
body.class-2 {
@include content($color-3, $color-4);
}
这篇关于根据选择器在Sass中设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!