如何在mat-select中实现已选中mat-option选项的垂直居中
appearance="fill"模式下的mat-form-field即使配置了[floatLabel]="'never'"隐藏标签,默认也会在容器顶部为标签预留内边距,这是选中项无法垂直居中的核心原因。
解决方法
首先给mat-form-field添加自定义类名实现样式隔离,避免影响其他组件:
<mat-form-field appearance="fill" [floatLabel]="'never'" class="centered-select"> <mat-select> <!-- 你的mat-option选项代码 --> </mat-select> </mat-form-field>
再根据你的使用场景添加对应样式:
- 组件内写样式(需穿透组件样式封装)
::ng-deep .centered-select .mat-mdc-form-field-infix { padding-top: 0 !important; min-height: auto !important; display: flex; align-items: center; }
*如果使用Angular Material v14及之前的非MDC版本,将类名中的mdc删除,修改为.mat-form-field-infix即可。
- 全局样式文件中写(推荐,无样式污染风险)
直接在项目根目录的全局样式文件(通常为styles.scss/styles.css)中添加以下代码:
.centered-select .mat-mdc-form-field-infix { padding-top: 0 !important; min-height: auto !important; display: flex; align-items: center; }
内容的提问来源于stack exchange,提问作者norty
相关产品推荐
相关产品推荐

