Angular Material v15自定义主题字体后部分文本未生效问题
自定义Angular Material v15主题字体时的继承问题
自定义Angular Material v15主题字体时,<mat-card-title>、<mat-card-action>等组件文本能正确应用自定义字体,但<p>、<span>、<mat-card-content>这类元素仍默认使用Roboto字体,疑问这些元素是否应该继承body-1样式?
复现步骤
- 在index.html中引入Google字体
- 在styles.scss中配置自定义字体为全局默认
配置代码
$theme-primary: mat.define-palette(mat.$indigo-palette); $theme-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400); $my-typography: mat.define-typography-config( $font-family: "'Nerko One', cursive", ); $theme: mat.define-light-theme( ( color: ( primary: $theme-primary, accent: $theme-accent, ), typography: $my-typography, ) ); @include mat.all-component-themes($theme);
已尝试多种配置方法均无效,仅全局硬编码字体可行,但不希望采用该方式。
问题原因与解决方案
Angular Material的组件主题仅会为组件内部的特定UI元素(如标题、按钮)绑定排版样式,原生元素(<p>、<span>)以及<mat-card-content>这类容器组件,默认不会自动继承body-1的排版配置。要让这些元素应用自定义字体,可通过以下方式处理:
1. 全局应用排版层级样式
在styles.scss中添加mat.typography-hierarchy混入器,它会自动将自定义排版应用到html、body、p、h1-h6等原生元素上:
$my-typography: mat.define-typography-config( $font-family: "'Nerko One', cursive", ); $theme: mat.define-light-theme( ( color: ( primary: $theme-primary, accent: $theme-accent, ), typography: $my-typography, ) ); // 全局应用排版样式到基础元素 @include mat.typography-hierarchy($my-typography); @include mat.all-component-themes($theme);
2. 为目标元素单独应用样式
如果不想全局覆盖,可针对特定元素或容器添加样式:
- 使用Angular Material内置类:给
<mat-card-content>或原生元素添加mat-body-1类:
<mat-card-content class="mat-body-1"> <p>这部分文本会使用自定义字体</p> </mat-card-content>
- 通过SCSS混入器自定义样式:在组件样式或全局样式中为目标元素应用排版层级:
.mat-card-content, p, span { @include mat.typography-level($my-typography, body-1); }
内容的提问来源于stack exchange,提问作者Julien
相关产品推荐
相关产品推荐

