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

升级至Angular 18 Material 3后,如何配置字体大小?

在Angular 18 Material 3中自定义字体大小及排版样式的方法

Material 3的排版体系基于Material Design 3的类型比例系统,和Material 2的API有明显差异,你可以通过以下步骤自定义字体大小、行高、字重等排版属性:


1. 定义自定义M3排版配置

使用mat.define-typography-config替代M2的mat.m2-define-typography-config,同时注意M3的排版层级名称和M2的对应关系:

  • M2的body-1 → M3的body-large
  • M2的body-2 → M3的body-medium
  • M2的button → M3的label-large(M3按钮默认使用该层级)

示例代码:

@use '@angular/material' as mat;

// 自定义M3排版配置
$custom-typography: mat.define-typography-config(
  $font-family: 'Roboto, "Helvetica Neue", sans-serif',
  // 对应原M2的body-1配置
  $body-large: mat.define-typography-level(14px, 20px, 400),
  // 对应原M2的body-2配置
  $body-medium: mat.define-typography-level(14px, 24px, 500),
  // 对应原M2的button配置
  $label-large: mat.define-typography-level(14px, 36px, 500, $letter-spacing: 0.014rem)
);

2. 将自定义排版应用到项目中

你需要把自定义排版配置传入核心样式和主题中,确保所有组件都使用该配置:

方式一:与现有主题集成

如果你的m3-theme文件中已经定义了颜色、密度配置,可以重新生成主题并传入自定义排版:

@use '@angular/material' as mat;
@use 'm3-theme';

// 基于原主题的颜色、密度,生成带自定义排版的浅色主题
$custom-light-theme: mat.define-light-theme(
  $color: m3-theme.$light-color-config,
  $typography: $custom-typography,
  $density: m3-theme.$light-density-config // 若无密度配置可省略
);

// 初始化核心样式时传入自定义排版
@include mat.core($custom-typography);
// 应用所有组件的排版样式
@include mat.all-component-typographies($custom-typography);

html {
  // 应用带自定义排版的主题
  @include mat.all-component-themes($custom-light-theme);
}

方式二:直接全局应用排版(不修改主题)

如果不需要调整主题的颜色/密度,也可以直接将自定义排版传入mat.core()和mat.all-component-typographies():

@use '@angular/material' as mat;
@use 'm3-theme';

@include mat.core($custom-typography);
@include mat.all-component-typographies($custom-typography);

html {
  @include mat.all-component-themes(m3-theme.$light-theme);
}

关键说明

  • M3的排版层级完全遵循Material Design 3的规范,所有层级名称可通过mat.$typography-levels变量查看完整列表
  • mat.define-typography-level的参数顺序为:$font-size, $line-height, $font-weight,可选参数包括$letter-spacing、$text-transform等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 19:31:17