升级Angular Material至6版本后排版配置异常问题
解决Angular Material 6升级后标题元素(h1-h6)样式不生效的问题
我升级Angular Material到6.x版本时也踩过这个坑!问题根源在于Angular Material 6对排版系统的默认行为做了变更——之前的版本会自动把自定义排版样式映射到原生<h1>至<h6>标签,但从v6开始,这个自动绑定被移除了,需要我们手动显式配置。
原因拆解
mat-core()混合宏只会初始化你定义的核心排版配置,但不会自动将这些样式关联到原生HTML标题元素。要完成这个映射,必须调用专门的混合宏来实现。
解决方案
只需在自定义排版配置和mat-core()调用之后,添加mat-typography-hierarchy()混合宏,它会自动把你定义的headline、title等层级样式对应到<h1>至<h6>标签上:
$custom-typography: mat-typography-config( $font-family: 'Roboto, sans-serif', // Large, one-off headers, usually at the top of the page. $display-4: mat-typography-level(112px, 112px, 300), $display-3: mat-typography-level(56px, 56px, 400), $display-2: mat-typography-level(45px, 48px, 400), $display-1: mat-typography-level(34px, 40px, 400), // h1 $headline: mat-typography-level(24px, 32px, 400), // h2 $title: mat-typography-level(20px, 32px, 500), // h3 $subheading-2: mat-typography-level(16px, 28px, 400), // h4 $subheading-1: mat-typography-level(15px, 24px, 400), // Bolder body text. $body-2: mat-typography-level(14px, 24px, 500), // Base body text. $body-1: mat-typography-level(18px, 20px, 400), // Smaller body and hint text. $caption: mat-typography-level(12px, 20px, 400), // Buttons and anchors. $button: mat-typography-level(18px, 14px, 300), // Line-height must be unit-less fraction of the font-size. $input: mat-typography-level(18px, 1.2, 300) ); @include mat-core($custom-typography); // 添加这一行,自动映射排版样式到h1-h6等原生元素 @include mat-typography-hierarchy($custom-typography);
可选:单独配置特定标题标签
如果你不需要全局应用所有层级样式,也可以单独给指定标题标签绑定样式,比如:
// 仅给h1和h2应用自定义排版样式 @include mat-h1($custom-typography); @include mat-h2($custom-typography);
额外提示
确保这段SCSS代码放在你定义Angular Material主题的文件中,并且已经正确导入了Material的SCSS基础文件,这样样式才能被正常编译和应用到项目里。
内容的提问来源于stack exchange,提问作者Da-Vi
相关产品推荐
相关产品推荐

