Angular Material v18如何修改字体族?已尝试旧方案无效
Angular Material v18 修改字体族的有效方案
步骤1:确保目标字体已加载
首先需确保要使用的字体(如Open Sans)已被引入到项目中,可以通过在index.html添加字体链接:
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap" rel="stylesheet">
或通过SCSS导入本地字体文件。
步骤2:在全局样式文件中配置自定义排版
在项目的全局样式文件(通常为styles.scss)中,按照以下方式配置:
// 导入Angular Material的SCSS模块 @use '@angular/material' as mat; // 定义自定义排版配置,核心是设置$font-family $custom-typography: mat.define-typography-config( $font-family: 'Open Sans', sans-serif, // 可选:根据需求调整各级别文本的字号、行高、字重 $body-1: mat.define-typography-level(16px, 24px, 400), $headline-1: mat.define-typography-level(96px, 112px, 300) ); // 将核心排版样式应用到根元素 :root { @include mat.core-typography($custom-typography); } // 为所有Material组件应用自定义排版 @include mat.all-component-typographies($custom-typography);
结合主题色配置(可选)
如果需要同时配置主题颜色和自定义字体,可将排版配置传入主题定义:
// 定义主题颜色配置 $custom-color-config: mat.define-color-config( $primary: mat.define-palette(mat.$indigo-palette), $accent: mat.define-palette(mat.$pink-palette) ); // 整合颜色与排版配置生成主题 $custom-theme: mat.define-theme( $color-config: $custom-color-config, $typography-config: $custom-typography ); // 应用完整主题样式 :root { @include mat.core-theme($custom-theme); @include mat.all-component-themes($custom-theme); }
关键说明
- Angular Material v18 使用
mat.define-typography-config作为全局排版配置的入口,$font-family是控制全局字体族的核心参数。 - 必须通过
mat.core-typography将排版样式注入到全局根元素,同时通过mat.all-component-typographies确保所有Material组件应用该字体。
内容的提问来源于stack exchange,提问作者Alaksandar Jesus Gene
相关产品推荐
相关产品推荐

