【问题标题】:Scss Variable based on class基于类的 Scss 变量
【发布时间】:2019-03-31 10:38:03
【问题描述】:

我正在尝试为我的一个项目做主题,而我曾经使用 css 变量来做同样的事情。我正在定义css变量如下

.theme-1 {
    --var-1: #ffe;
    --var-2: #000;
}

.theme-2 {
    --var-1: #fff;
    --var-2: #000;
}

在 html 中我应用了如下主题

<div [ngClass]="'theme-1'">
<!--content>

<-->
</div>

一切都很好,除了 Here 提到的 IE -11 之前不支持 css 变量。

问题

有什么方法可以用 scss 变量实现这一点,以便我可以定义全局变量并根据类更改值。

注意:我在我的项目中使用 angular,因此我也必须担心视图封装。如果可以通过默认封装实现答案,那就太好了。

提前致谢。

【问题讨论】:

    标签: angular sass css-variables scss-mixins


    【解决方案1】:

    由于 SASS 是自顶向下编译的,您可以为每个主题重新定义变量,并复制常用样式,这些样式将被编译为使用正确的变量值。

    _dark-theme.scss

    // Variables for dark theme
    $background-color: #333;
    $color: #fff;
    

    _light-theme.scss

    // Variables for light theme
    $background-color: #eee;
    $text-color: #333;
    

    _common-styles.scss

    // Styles used across all themes, uses theme variables
    body {
        background: $background-color;
        color: $text-color;
    }
    

    ma​​in.scss

    .dark-theme {
        @import "dark-theme";
        @import "common-styles";
    }
    
    .light-theme {
        @import "light-theme";
        @import "common-styles";
    }
    

    然后在 html 的顶层使用所需的主题类。

    <body class="dark-theme">
        ...
    </body>
    

    【讨论】:

    • 其中有多个具有特定样式定义的文件,例如我没有导入变量的按钮.scss。届时将再次采用默认值!
    • 您可以在buttons.scss 中的import 语句或您要导入默认变量的任何其他地方添加一个sass 变量作为标志。 main.scss: $skip-var-import: true; --buttons.scss: @if not($skip-var-import) { @import 'default-variables'; }
    【解决方案2】:

    我个人更喜欢为此使用函数,但您也可以使用 mixin 来实现。

    创建一个地图,其属性绑定到与您拥有的主题一样多的值。
    然后,定义一个自定义属性来获取此地图并返回所需的值。

    $theme: (
      color: (#000, #FFF),
      border: (dashed, solid),
      // etc.
    );
    
    @function theme($property, $index) {
      @return nth(map-get($theme, $property), $index);
    }
    
    .light.foo {
      color: theme(color, 1);
    }
    
    .dark.foo {
      color: theme(color, 2);
    }
    

    Demo SassMeister

    【讨论】:

    • 嗯可能有用,但我有不同的文件定义主题变量。使用函数需要一个具有定义值的静态 @theme 变量,在我的情况下这是不可能的,因为我有不同的主题文件。还有其他的 elagent 方式吗?
    猜你喜欢
    • 2018-10-30
    • 2015-04-07
    • 1970-01-01
    • 2023-04-03
    • 2019-04-06
    • 2016-01-12
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多