如何在Angular v15中缩小包含mat-select的mat-form-field高度?
缩小Angular 15中带mat-select的Outline样式mat-form-field高度的解决方案
使用Angular v15,当前采用Material组件文档的默认代码,仅包含outline样式的mat-form-field和mat-select,代码如下:
<mat-form-field appearance="outline"> <mat-select> @for (food of foods; track food) { <mat-option [value]="food.value">{{ food.viewValue }}</mat-option> } </mat-select> </mat-form-field>
当前mat-form-field高度偏大,期望实现更紧凑的高度(忽略文本截断)。
解决方案:自定义CSS调整样式
通过覆盖Angular Material的默认样式,调整内边距、高度等属性来实现紧凑效果,在组件的样式文件(如.component.scss)中添加以下样式:
/* 调整outline边框的整体高度 */ ::ng-deep .mat-mdc-form-field-outline { height: 40px !important; /* 根据需求自定义高度 */ } /* 保持outline边框的圆角一致 */ ::ng-deep .mat-mdc-form-field-outline-start, ::ng-deep .mat-mdc-form-field-outline-end { border-radius: 4px !important; } /* 缩小mat-select的最小高度 */ ::ng-deep .mat-mdc-select { min-height: 32px !important; } /* 调整表单域内部的内边距和高度 */ ::ng-deep .mat-mdc-form-field-infix { padding: 0.5em 0 !important; min-height: 32px !important; } /* 调整选择器触发器的高度和行高,保证文字垂直居中 */ ::ng-deep .mat-mdc-select-trigger { height: 32px !important; line-height: 32px !important; }
注意事项
- 使用
::ng-deep是为了穿透组件的样式封装,若在全局样式文件中编写,可省略::ng-deep; - 可根据实际需求微调
height、padding等数值,确保元素垂直居中显示; - 若不想使用
!important,可通过提高CSS选择器的优先级(如结合组件类名)来覆盖默认样式。
内容的提问来源于stack exchange,提问作者Tristate
相关产品推荐
相关产品推荐

