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

如何在Angular Material 17中减小Mat表单字段高度?

Angular Material 17(MDC)表单字段高度调整方案

我们将Angular项目从13版本升级至17版本,同步完成Angular Material到17(MDC)版本的升级后,遇到表单字段无法缩小高度的问题。

问题对比

  • Angular Material 13 表单样式:
    Angular Material 13表单
  • Angular Material 17 表单样式:
    Angular Material 17表单

核心原因

Angular Material 17基于Material Design Components(MDC)重构,表单字段的DOM结构、样式变量和布局逻辑完全重写,旧版本通过直接修改height或padding的方式不再生效。

可行解决方案

1. 使用官方内置的密度(Density)属性

Material 17提供了密度系统控制组件尺寸,通过density属性直接调整表单字段高度:

<!-- 数值越小组件越紧凑,可选范围-5到0,默认值为0 -->
<mat-form-field density="-2">
  <input matInput placeholder="示例输入框">
</mat-form-field>

也可以全局配置密度,在主题文件中设置:

@use '@angular/material' as mat;

$theme: mat.define-theme(
  (
    color: (
      primary: mat.define-palette(mat.$indigo-palette),
      accent: mat.define-palette(mat.$pink-palette),
    ),
    typography: mat.define-typography-config(),
    density: -2 // 全局设置所有组件的密度
  )
);

2. 自定义CSS覆盖MDC样式

若密度属性无法满足需求,可通过深度选择器覆盖MDC内部样式:

:host::ng-deep .mdc-text-field--filled {
  height: 40px;
  padding-top: 12px;
  padding-bottom: 4px;
}

:host::ng-deep .mdc-floating-label {
  font-size: 14px;
  transform: translateY(-10px);
}

:host::ng-deep .mat-mdc-form-field-infix {
  padding: 0;
  min-height: auto;
}

注意:使用:host::ng-deep时,建议配合组件的encapsulation: ViewEncapsulation.None或限定样式作用范围,避免全局样式污染。

3. 调整Typography配置

通过修改主题排版配置,缩小表单字体大小间接带动高度缩小:

@use '@angular/material' as mat;

$custom-typography: mat.define-typography-config(
  (
    input: mat.define-typography-level(14px, 20px, 400),
  )
);

$theme: mat.define-theme(
  (
    typography: $custom-typography,
    // 其他主题配置项
  )
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 20:51:01