如何在Angular项目中为mat-button添加自定义颜色?
自定义Angular Material按钮颜色的两种方法
方法一:直接用CSS覆盖(适合单个/少量按钮)
这种方式最简单直接,直接在你现有的.centered-button类里添加自定义颜色样式,覆盖Material默认的主题样式。如果组件内样式被视图封装隔离导致不生效,可以加上::ng-deep深度选择器。
修改后的样式代码:
.centered-button { display: flex; align-items: center; justify-content: center; padding: 8px 16px; /* 自定义背景色 */ background-color: #2ecc71 !important; /* 自定义文字颜色 */ color: #ffffff !important; } /* 鼠标悬停状态 */ .centered-button:hover { background-color: #27ae60 !important; } /* 点击激活状态 */ .centered-button:active { background-color: #229954 !important; } .button-text { margin-left: 5px; font-size: 14px; }
如果组件内样式不生效,改用深度选择器写法:
::ng-deep .centered-button.mat-raised-button { background-color: #2ecc71; color: #ffffff; } ::ng-deep .centered-button.mat-raised-button:hover { background-color: #27ae60; } ::ng-deep .centered-button.mat-raised-button:active { background-color: #229954; }
HTML部分无需修改color属性,保留原有代码即可:
<button (click)="gotoDashboardHome()" mat-raised-button class="centered-button"> <mat-icon>reply</mat-icon> <span class="button-text">Back</span> </button>
方法二:自定义Material主题(适合全局复用)
如果你希望把自定义颜色当成主题色全局使用(像primary/accent那样),可以修改全局样式文件(styles.scss)来扩展Material主题。
步骤1:定义自定义调色板并扩展主题
在styles.scss中添加以下代码:
@import '@angular/material/theming'; // 1. 定义自定义调色板(可使用Material预设调色板,也可完全自定义颜色) $custom-button-color: mat.define-palette( ( 50: #f8f0fc, 100: #f1e0fa, 200: #e4c5f7, 300: #d7aaf4, 400: #cb91f2, 500: #bf76ef, // 默认按钮背景色 600: #b162eb, // 悬停状态颜色 700: #a24de6, // 激活状态颜色 800: #933ae2, 900: #7a1cdb, A100: #e8bfff, A200: #d48fff, A400: #c05fff, A700: #b340ff, ) ); // 2. 创建自定义主题,加入自定义颜色 $custom-theme: mat.define-light-theme( ( color: ( primary: mat.define-palette(mat.$indigo-palette), accent: mat.define-palette(mat.$pink-palette), warn: mat.define-palette(mat.$red-palette), custom: $custom-button-color, // 新增自定义颜色变量 ) ) ); // 3. 为mat-button注册自定义颜色的样式 @mixin mat-button-custom-theme($theme) { $color-config: mat.get-color-config($theme); $custom-color: map-get($color-config, custom); .mat-raised-button.custom-color { background-color: mat.get-color-from-palette($custom-color, default); color: mat.get-contrast-color($custom-color, default); &:hover { background-color: mat.get-color-from-palette($custom-color, 600); } &:active { background-color: mat.get-color-from-palette($custom-color, 700); } } } // 4. 应用主题和自定义按钮样式 @include mat.all-component-themes($custom-theme); @include mat-button-custom-theme($custom-theme);
步骤2:在HTML中使用自定义颜色
给按钮添加custom-color类即可:
<button (click)="gotoDashboardHome()" mat-raised-button class="centered-button custom-color"> <mat-icon>reply</mat-icon> <span class="button-text">Back</span> </button>
内容的提问来源于stack exchange,提问作者Avinash Gaikwad
相关产品推荐
相关产品推荐

