使用CSS变量创建角度材质主题

问题描述 投票:4回答:2

我正在开发一个需要在运行时可以设置主题的项目。所以我创建了一个将SCSS变量与CSS变量结合起来的主题系统。这是它的外观。

:root {
  --primary-color: 196;
}


// Primary
$primary-100: hsl(var(--primary-color), 90%, 98%);
$primary-400: hsl(var(--primary-color), 90%, 65%);
$primary-main: hsl(var(--primary-color), 90%, 50%);
$primary-700: hsl(var(--primary-color), 90%, 30%);
$primary-900: hsl(var(--primary-color), 90%, 10%);

虽然这对我的自定义组件非常有效,但我很难使它与Material设计主题系统一起工作。

我的想法是,我将按照Angular材料文档中的说明创建主题,而不是使用静态颜色,我将使用我的SCSS变量。这就是我的theme.scss文件的样子。

@import '~@angular/material/theming';
@import 'var.scss';

@include mat-core();

$shop-primary: (
  50: $primary-100,
  100: $primary-100,
  200: $primary-200,
  300: $primary-300,
  400: $primary-400,
 // ..... all other colors
  contrast: (
    50: $black-87-opacity,
    100: $black-87-opacity,
    200: $black-87-opacity,
     // ..... all other colors
  )
);


$shop-app-primary: mat-palette($shop-primary);
$shop-app-accent:  mat-palette($shop-primary);
$shop-app-warn: mat-palette($shop-primary);


$shop-app-theme: mat-light-theme($shop-app-primary, $shop-app-accent, $shop-app-warn);

@include angular-material-theme($shop-app-theme);

我收到一个错误:

 Argument `$color` of `rgba($color, $alpha)` must be a color

假设因为Angular Material mixin期待color而不是hsl()值。

所以我的问题是我如何能够使用运行时CSS变量创建自定义材质主题?

css angular sass angular-material
2个回答
4
投票

如果你升级到@ angular / material 7.3.4 CSS变量将主要起作用。只有使用不透明度的riples和其他东西需要一点修复。我为我的项目使用rgba(),但它也适用于hsla()

包括这个:

@function mat-color($palette, $hue: default, $opacity: null) {
    @if type-of($hue) == number and $hue >= 0 and $hue <= 1 {
        @return mat-color($palette, default, $hue);
    }

    $color: map-get($palette, $hue);

    @if (type-of($color) != color) {
        @if ($opacity == null){
            @return $color;
        }

        // Here is the change from the original function:
        // If the $color resolved to something different from a color, we assume it is a CSS variable
        // in the form of rgba(var(--rgba-css-var),a) and replace the 'a' value.
        @return #{str-slice($color, 0, str-index($color, ',')) + $opacity + ')'};
    }

    @return rgba($color, if($opacity == null, opacity($color), $opacity));
}

直接之后:

@import '~@angular/material/theming';

并定义你喜欢的颜色:

--primary-color-50-parts: 0,158,224;
// ... all other colors

$color-primary: (
    50: rgba(var(--primary-color-50-parts), 1),
    // ... all other colors
);

如果您在地图中定义颜色,如下所示:

50: hsla(var(--primary-color), 90%, 98%, 1);

那么你需要将sass函数中的str-index($ color,',')更改为查找字符串中最后一个','的内容。不幸的是,我的sass知识仅涵盖最低限度,我不知道该怎么做:/


-2
投票

Sooo ... css变量是运行时,而不是编译时。 SASS不知道如何处理它们。您应该能够使用SCSS的$ {}插值来重构您的css变量,并且所有内容仍然可以正常工作。 http://sass-lang.com/documentation/file.SASS_REFERENCE.html#interpolation_

$primary-color: 196;

:root {
  --primary-color: #{$primary-color};
}

$primary-100: hsl($primary-color, 90%, 98%);
© www.soinside.com 2019 - 2024. All rights reserved.