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

Angular Material 3 排版样式不生效问题及正确用法咨询

Angular Material 3 排版样式不生效问题及正确用法咨询

我来帮你梳理下这个问题——你遇到的情况其实是Angular Material 3(简称M3)和之前版本在排版应用方式上的核心变化导致的,下面一步步拆解原因和解决方案:

问题出在哪?

  1. 排版配置错误:你在mat.theme()里直接写了typography: Roboto,但M3要求这里传入的是排版配置对象,不是单纯的字体名称,所以这个配置其实没生效。
  2. mat-typography类不再自动生成:M3移除了自动生成全局mat-typography类的逻辑,所以你在body上加了这个类,但Chrome dev工具里根本看不到对应的样式,自然字体不会变成Roboto。

正确的排版配置&应用方式

第一步:先修正全局主题的排版配置

在styles.scss里,我们需要先定义基于Roboto的排版配置对象,再传入主题:

@use '@angular/material' as mat;

// 1. 定义自定义排版配置,指定Roboto为默认字体族
$roboto-typography: mat.define-typography-config(
  $font-family: 'Roboto, sans-serif',
  // 可选:你可以自定义各层级的样式(比如body、headline、button等)
  $body-large: mat.define-typography-level(
    $font-size: 16px,
    $line-height: 24px,
    $font-weight: 400
  ),
  $button: mat.define-typography-level(
    $font-size: 14px,
    $line-height: 20px,
    $font-weight: 500
  )
);

html {
  color-scheme: light dark;
  // 2. 将排版配置传入主题
  @include mat.theme((
    color: mat.$azure-palette,
    typography: $roboto-typography,
  ));
}

第二步:选择一种方式全局应用排版

你可以根据习惯选下面任意一种:

方式1:重新生成mat-typography类(兼容旧写法)

如果你想继续用body上的mat-typography类,只需在styles.scss里添加一行,手动生成这个类的样式:

// 在主题定义之后,生成mat-typography类
@include mat.typography-classes($roboto-typography);

这样重启服务后,Chrome dev工具里就能看到mat-typography类的样式,所有加了这个类的元素(比如你的body)就会自动应用Roboto字体。

方式2:用M3的CSS变量全局应用(推荐M3新方式)

M3会自动生成一系列排版相关的CSS变量(比如--mat-sys-body-large-font-family),你可以直接在全局样式里给body设置这些变量,不需要依赖类:

body {
  font-family: var(--mat-sys-body-large-font-family);
  font-size: var(--mat-sys-body-large-font-size);
  line-height: var(--mat-sys-body-large-line-height);
  font-weight: var(--mat-sys-body-large-font-weight);
  letter-spacing: var(--mat-sys-body-large-letter-spacing);
}

这种方式更贴合M3的设计思路,不需要额外生成类,直接利用框架提供的变量。

方式3:在组件内局部应用

如果只需要在特定组件(比如app.component)里应用排版,可以在组件的scss文件里用mat.typography-level混合宏:

// app.component.scss
:host {
  @include mat.typography-level($roboto-typography, body-large);
}

最后验证

做完上面的修改后,重启Angular开发服务,打开Chrome dev工具检查元素:

  • 如果用方式1:body的mat-typography类会显示对应的Roboto样式
  • 如果用方式2:body的样式里会看到通过CSS变量引用的Roboto字体

这样你的普通文本、按钮标签就都会显示Roboto字体了~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 14:32:58