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

Angular中修改Mat-Form-Field样式为普通文本框及后续调整

解决Angular mat-form-field缩小尺寸及图标垂直居中问题

实现思路

  • 缩小20%尺寸:利用Angular Material表单字段基于字体大小的特性,通过缩放字体大小配合调整内边距、高度实现整体尺寸缩小,避免直接用transform导致布局错位。
  • 图标垂直居中:通过调整图标的对齐方式和父容器布局,确保图标与输入框文本在垂直方向居中对齐。

修改后的代码

HTML代码

<mat-form-field class="custom-form-field">
    <input matInput type="text" id="onSearch" (keyup)="keyUp($event)">
    <mat-icon matPrefix class="centered-icon">search</mat-icon>
</mat-form-field>

CSS代码

/* 基础样式:去除默认边框并调整尺寸 */
.custom-form-field {
  /* 缩小20%:默认字体大小16px,设为12.8px(16*0.8),配合调整内边距 */
  font-size: 12.8px;
  padding-top: 4px; /* 原5px缩小20% */
  padding-bottom: 0;
  line-height: 1;
  height: 32px; /* 按比例缩小后的高度,可根据需求微调 */
}

.custom-form-field .mat-form-field-outline-thick,
.custom-form-field .mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick {
  border-color: black !important;
  color: black !important;
  opacity: 1 !important;
}

.custom-form-field .mat-input-element {
  caret-color: black !important;
  padding-top: 0;
  padding-bottom: 0;
}

/* 图标垂直居中 */
.custom-form-field .centered-icon {
  display: flex;
  align-items: center;
  height: 100%;
  /* 若仍有偏移,可微调margin-top */
  /* margin-top: -2px; */
}

/* 调整表单字段内部容器,确保整体对齐 */
.custom-form-field .mat-form-field-infix {
  padding: 0.375em 0; /* 按缩小后的字体大小调整内边距 */
  border-top: 0; /* 去除默认顶部边框,更贴近普通文本框 */
}

说明

  • 字体大小设为原大小的80%是实现整体尺寸缩小20%的核心,Angular Material的表单元素会基于字体大小自动适配其他尺寸。
  • 图标使用flex布局的align-items: center配合高度100%,确保和输入框内容垂直居中;若实际显示仍有偏移,可微调margin-top值。
  • 去除mat-form-field-infix的顶部边框,让组件更接近普通文本框的视觉效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 07:35:09