如何为Angular M3主题添加自定义调色板及自定义颜色?
Angular M3 主题自定义调色板与颜色解决方案
问题1:添加类似primary的自定义命名调色板(如custom)
可以直接添加自定义调色板,步骤如下:
- 定义自定义调色板
用mat.define-palette()创建专属调色板,既可以基于Material内置调色板修改,也可以完全自定义色值:
// 方式1:基于内置调色板修改 $_custom: mat.define-palette(mat.$indigo-palette, 500, 100, 900); // 方式2:完全自定义色值(含对比度文本色) $_custom: mat.define-palette( ( 50: #e8eaf6, 100: #c5cae9, 200: #9fa8da, 300: #7986cb, 400: #5c6bc0, 500: #3f51b5, 600: #3949ab, 700: #303f9f, 800: #283593, 900: #1a237e, contrast: ( 50: #000000, 100: #000000, 200: #000000, 300: #ffffff, 400: #ffffff, 500: #ffffff, 600: #ffffff, 700: #ffffff, 800: #ffffff, 900: #ffffff, ) ) );
- 将调色板加入主题配置
在mat.define-theme()的color节点下直接添加自定义调色板字段:
$light-theme: mat.define-theme( ( color: ( theme-type: light, primary: $_primary, tertiary: $_tertiary, // 加入自定义调色板 custom: $_custom, ), typography: ( brand-family: 'Roboto', bold-weight: 900, ), ) );
- 使用自定义调色板
和primary等内置调色板用法一致,通过mat-color()调用对应色阶:
.custom-card { background-color: mat-color($light-theme.custom, 500); color: mat-color($light-theme.custom, contrast-500); }
问题2:添加名为navigation-background的自定义颜色
在M3中通过custom-colors字段实现单颜色自定义,步骤如下:
- 定义颜色值
先声明你的目标颜色变量:
$nav-bg-light: #f5f5f5; $nav-bg-dark: #212121;
- 将颜色加入主题配置
在color节点下新增custom-colors对象,添加自定义颜色:
$light-theme: mat.define-theme( ( color: ( theme-type: light, primary: $_primary, tertiary: $_tertiary, custom-colors: ( navigation-background: $nav-bg-light, ) ), typography: ( brand-family: 'Roboto', bold-weight: 900, ), ) ); // 深色主题同步配置对应颜色 $dark-theme: mat.define-theme( ( color: ( theme-type: dark, primary: $_primary, tertiary: $_tertiary, custom-colors: ( navigation-background: $nav-bg-dark, ) ), typography: ( brand-family: 'Roboto', bold-weight: 900, ), ) );
- 使用自定义颜色
通过mat.get-color-from-theme()获取主题中的自定义颜色:
.navigation-bar { background-color: mat.get-color-from-theme($light-theme, custom-colors, navigation-background); }
内容的提问来源于stack exchange,提问作者Thorsten Rintelen
相关产品推荐
相关产品推荐

