我有一个网站,使用几种不同的“主”颜色。一般的HTML布局保持不变,只有颜色变化取决于内容。
我想知道是否可以根据CSS选择器设置一个颜色变量。通过这种方式,我可以用几个变量作为我网站的主题,让Sass填充颜色。
例如:
$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;
}我想用一个混合器来做这个,但是我想知道是否有更好的方法--也许有一个函数?我和Sass相处得不太好,所以我会很感激你的帮助。
发布于 2013-08-07 19:46:38
我认为混和是答案。(就像我写的,变量不能工作。)
@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:
body.class-1 {
background: #444444;
color: #555555; }
body.class-2 {
background: #666666;
color: #777777; }如果要在SCSS文件中将颜色值组合在一起,可以将变量与混合器结合使用:
$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);
}发布于 2020-07-13 09:42:04
正如sass文档很好地解释的那样(https://sass-lang.com/documentation/variables):
我们可以利用这一点,使用sass和css变量的组合来实现您想要的结果:
//theme colors
$red-cosmo: #e01019;
$green-cosmo: #00c398;
$primary-color: var(--primary-color);
body{
--primary-color: #{$red-cosmo};
}
body.univers-ride{
--primary-color: #{$green-cosmo};
}所以当我叫我的sass变量$主色时,它将打印为我的css变量“var(-主颜色)”,它将扩展为$green-cosmo,只有当我的身体有"univers-ride“类时,它才会是$red-cosmo默认的颜色。
发布于 2013-08-08 07:22:37
如果你真的想变黑,你也可以在一个变量(如$scheme1: class1 #333 #444 )中定义不同的配色方案,其中第一个值总是名称,然后是该方案中的所有颜色。
然后您可以使用@each
// Define your schemes with a name and colors
$scheme1: class1 #444 #555;
$scheme2: class2 #666 #777;
$scheme3: class4 #888 #999;
// Here are your color schemes
$schemes: $scheme1 $scheme2 $scheme3;
@each $scheme in $schemes {
// Here are the rules specific to the colors in the theme
body.#{nth($scheme, 1)} .content {
background-color: nth($scheme, 2);
color: nth($scheme, 3);
}
}这将汇编成:
body.class1 .content {
background-color: #444444;
color: #555555; }
body.class2 .content {
background-color: #666666;
color: #777777; }
body.class4 .content {
background-color: #888888;
color: #999999; }显然,如果您不想将body.class1和.content组合到选择器中,您只需指定一个content($main, $default)并使用nth在@each中调用它,就像上面的代码一样,但重点是您不必为每个类编写规则。
编辑关于在Sass中动态创建或引用变量和将字符串和变量合并为带有SASS的变量有很多有趣的答案。
https://stackoverflow.com/questions/18112238
复制相似问题