使用 CSS 变量创建角度材质主题 [英] Create angular material theme with CSS variables

查看:19
本文介绍了使用 CSS 变量创建角度材质主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个需要在运行时可主题化的项目.所以我创建了一个主题系统,将 SCSS 变量与 CSS 变量相结合.这是它的样子.

I'm working on a project that requires to be themeable at runtime. So I created a theme system that combines SCSS variable with CSS Variables. This is how it looks.

: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 design 主题系统一起工作.

While this works amazingly with my custom components, I'm having a hard time making it work with the Material design theme system.

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

My thinking was that I will create the theme as explained in the Angular material docs, and instead of using static colors, I will use my SCSS variables. this is how my theme.scss file looks like.

@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() 值.

Presumingly because the Angular Material mixin is expecting a color and not a hsl() value.

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

推荐答案

我创建了一个 little图书馆 使这更容易一些.

I created a little library to make this a little easier.

你可以这样使用它:

  1. 安装:

npm i angular-material-css-vars -S

  • 然后从主样式表文件中删除任何现有的 @import '~@angular/material/theming';.

    改为将其添加到您的主样式表中:

    Add this to your main stylesheet instead:

    @import '~angular-material-css-vars/main';
    @include initMaterialCssVars();
    

  • 像这样更改主题颜色:

  • Change the main theme color like so:

    import {MaterialCssVarsService} from 'angular-material-css-vars';
    
    export class SomeComponentOrService {
      constructor(public materialCssVarsService: MaterialCssVarsService) {
        const hex = '#3f51b5';
        this.materialCssVarsService.changePrimaryColor(hex);
      }
    }
    

  • 这篇关于使用 CSS 变量创建角度材质主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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