You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Angular Material侧边栏列表项设置自定义文字颜色?

解决Angular Material List Item文字颜色自定义问题

问题场景

现有如下Angular Material侧边栏及列表代码:

<mat-sidenav #sidenav opened="true" mode="side" class="sidenav">
  <mat-list role="list">
    <mat-list-item role="listitem" >Item 1</mat-list-item>
    <mat-list-item role="listitem" >Item 2</mat-list-item>
    <mat-list-item role="listitem" >Item 3</mat-list-item>
  </mat-list>
</mat-sidenav>

尝试通过添加自定义类.text-color(定义color: white;)或内联样式修改列表项文字颜色,但文字始终显示黑色。

原因分析

Angular默认启用样式隔离,组件内的CSS无法穿透到Angular Material组件的内部DOM结构;同时Material组件自身的样式优先级较高,普通选择器无法覆盖。

解决方案

1. 使用::ng-deep穿透样式隔离

在组件的CSS文件中,通过::ng-deep打破样式隔离,直接作用于Material组件内部元素:

/* 给mat-list添加text-color类后,作用于其下所有列表项 */
::ng-deep .text-color mat-list-item {
  color: white;
}

对应的HTML修改:

<mat-list role="list" class="text-color">
  <!-- 列表项 -->
</mat-list>

或者直接全局作用于所有mat-list-item:

::ng-deep mat-list-item {
  color: white;
}

2. 提升CSS选择器优先级

直接定位到Material列表项内部的文本承载元素,通过更具体的选择器覆盖默认样式:

.mat-list-item .mat-list-item-content span {
  color: white;
}

3. 内联样式结合!important(应急方案)

如果需要快速测试,可在列表项中使用!important强制覆盖默认样式(不推荐长期使用,会增加样式维护成本):

<mat-list-item role="listitem" style="color: white !important;">Item 1</mat-list-item>

4. 全局主题自定义(全局生效)

在项目根目录的styles.scss中,修改Material主题并自定义列表文本颜色:

@import '@angular/material/theming';

@include mat-core();

// 定义自定义主题色板
$custom-primary: mat-palette($mat-blue);
$custom-accent: mat-palette($mat-pink, A200, A100, A400);
$custom-warn: mat-palette($mat-red);
$custom-theme: mat-light-theme($custom-primary, $custom-accent, $custom-warn);

@include angular-material-theme($custom-theme);

// 全局设置列表项文字颜色
.mat-list-item {
  color: white;
}

内容的提问来源于stack exchange,提问作者Brian Reinhold

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:32:39