如何将Angular Material的matInput高度调整至28px
调整Angular Material matInput高度至28px的解决方案
要将matInput的高度从默认56px改为28px,需要覆盖Angular Material组件的默认样式,以下是具体实现步骤:
1. 修改HTML结构
给mat-form-field添加自定义类(比如small-input),方便精准定位样式:
<mat-form-field class="example-form-field small-input"> <mat-label>Clearable input</mat-label> <input matInput type="text" [(ngModel)]="value"> @if (value) { <button matSuffix mat-icon-button aria-label="Clear" (click)="value=''"> <mat-icon>close</mat-icon> </button> } </mat-form-field>
2. 添加自定义样式
在全局样式文件(如styles.css)或组件的样式文件中,添加以下CSS代码(组件内样式需使用::ng-deep穿透Angular的样式封装):
/* 组件内样式需添加::ng-deep,全局样式无需 */ ::ng-deep .small-input { height: 28px; font-size: 14px; } ::ng-deep .small-input .mat-mdc-form-field-infix { padding: 0.25em 0; min-height: 28px; } ::ng-deep .small-input input.mat-mdc-input-element { padding-top: 0.25em; padding-bottom: 0.25em; } ::ng-deep .small-input .mat-mdc-form-field-label-wrapper { top: -0.5em; } ::ng-deep .small-input .mat-mdc-icon-button { width: 24px; height: 24px; line-height: 24px; } ::ng-deep .small-input .mat-icon { font-size: 18px; }
关键说明
- 全局样式中无需
::ng-deep,组件内样式必须添加才能穿透Angular的视图封装,修改Material组件的内部样式。 - 调整
min-height、padding、font-size等属性时,需保持标签、输入框、后缀按钮的布局对齐,避免错位。 - 若使用非MDC版本的Angular Material,需去掉类名中的
mdc前缀,对应调整为mat-form-field-infix、mat-input-element等类名。
内容的提问来源于stack exchange,提问作者Sergey
相关产品推荐
相关产品推荐

