SASS设置变量取决于CSS类 [英] SASS set variable depending on CSS class

查看:278
本文介绍了SASS设置变量取决于CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站使用几种不同的主要颜色。一般的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 a CSS-class. 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 if anyone could help me out. Appreciated.

谢谢。

推荐答案

=http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#mixins> mixin 是答案。 (我在写时,变量不会工作。)

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文件中将颜色值分组在一起, with 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设置变量取决于CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆