Angular中div内按钮无法垂直对齐的问题求助
解决Clear Filter按钮垂直对齐问题
先修正你代码里的一个拼写错误:按钮上的stye要改成style,否则按钮的内联样式不会生效。
针对按钮垂直对齐的需求,给你两个实用的解决思路:
思路1:用Flex布局替代Float(推荐)
Float布局本身不太好处理垂直对齐,换成Flex布局可以更轻松实现需求,而且代码更简洁:
<div style="width: 100%; display: flex; align-items: center;"> <div style="width: 70%;"> <mat-form-field appearance="standard"> <mat-label>Filter Table Data</mat-label> <input matInput [(ngModel)]="filter" (keyup)="applyFilter($event)"> </mat-form-field> </div> <div style="width: 30%; display: flex; justify-content: flex-end;"> <button style="display: flex; flex-direction: column; align-items: center;" mat-raised-button (click)="clearFilter(1)"> Clear Filter </button> </div> </div>
外层div设置display: flex; align-items: center;后,内部元素会自动垂直居中,同时右侧div加justify-content: flex-end;让按钮靠右显示。
思路2:保留Float布局的适配方案
如果一定要用Float布局,可以给右侧容器添加垂直居中的样式,同时外层容器清除浮动:
<div style="width: 100%; overflow: auto;"> <div style="width: 70%; float: left;"> <mat-form-field appearance="standard"> <mat-label>Filter Table Data</mat-label> <input matInput [(ngModel)]="filter" (keyup)="applyFilter($event)"> </mat-form-field> </div> <div style="width: 30%; float: right; display: flex; align-items: center; min-height: 64px;"> <button style="display: flex; flex-direction: column; align-items: center;" mat-raised-button (click)="clearFilter(1)"> Clear Filter </button> </div> </div>
- 外层div用
overflow: auto;清除浮动带来的布局问题 - 右侧div设置
display: flex; align-items: center;实现内部按钮垂直居中,min-height: 64px;是匹配mat-form-field的默认高度,确保对齐一致
内容的提问来源于stack exchange,提问作者user68288
相关产品推荐
相关产品推荐

