Angular mat-table单元格对齐异常,需将内容左对齐匹配表头
解决Angular Material Table单元格与表头左对齐的问题
问题描述
我已成功实现mat-table功能,但表格单元格对齐存在异常,希望将单元格内容设置为与表头一致的左对齐样式。当前表格显示效果对齐混乱,我已查阅相关讨论,但未能成功应用解决方案。
当前我的CSS代码如下:
table { width: 100%; }
HTML代码如下:
<h3> All Uploaded invoices:</h3> <div class="invoice-table mat-elevation-z8"> <table mat-table #table [dataSource]="invoices"> <ng-container matColumnDef="rating"> <th mat-header-cell *matHeaderCellDef> Rating </th> <td mat-cell *matCellDef="let invoice"> {{invoice.rating}} </td> </ng-container> <ng-container matColumnDef="amount"> <th mat-header-cell *matHeaderCellDef> Amount </th> <td mat-cell *matCellDef="let invoice"> {{invoice.amount}} </td> </ng-container> <ng-container matColumnDef="debtor"> <th mat-header-cell *matHeaderCellDef> Debtor </th> <td mat-cell *matCellDef="let invoice"> {{invoice.debtor}} </td> </ng-container> <ng-container matColumnDef="serial"> <th mat-header-cell *matHeaderCellDef> Serial </th> <td mat-cell *matCellDef="let invoice"> {{invoice.serial}} </td> </ng-container> <ng-container matColumnDef="dateout"> <th mat-header-cell *matHeaderCellDef> Dateout </th> <td mat-cell *matCellDef="let invoice"> {{invoice.dateout}} </td> </ng-container> <ng-container matColumnDef="expiration"> <th mat-header-cell *matHeaderCellDef> Expiration </th> <td mat-cell *matCellDef="let invoice"> {{invoice.expiration}} </td> </ng-container> <ng-container matColumnDef="daysleft"> <th mat-header-cell *matHeaderCellDef> Days left </th> <td mat-cell *matCellDef="let invoice"> {{invoice.daysleft}} </td> </ng-container> <ng-container matColumnDef="fid"> <th mat-header-cell *matHeaderCellDef> Fid </th> <td mat-cell *matCellDef="let invoice"> {{invoice.fid}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> <mat-paginator [pageSizeOptions]="[20, 100, 200]" showFirstLastButtons></mat-paginator> </div> <p><a [routerLink]="['/login']">Logout</a></p>
快速解决方法
其实很简单,直接针对Angular Material提供的表格单元格类写CSS就能搞定,覆盖它的默认对齐样式:
table { width: 100%; } /* 统一设置所有单元格和表头左对齐 */ .mat-cell, .mat-header-cell { text-align: left !important; justify-content: flex-start; }
要是你只想调整某几列,不想全局改,也可以给特定列加自定义类:
先在HTML的列定义里给表头和单元格加上类:
<ng-container matColumnDef="amount"> <th mat-header-cell *matHeaderCellDef class="left-align-col"> Amount </th> <td mat-cell *matCellDef="let invoice" class="left-align-col"> {{invoice.amount}} </td> </ng-container>
然后CSS里写:
.left-align-col { text-align: left !important; }
为啥这么管用?
Angular Material的mat-cell默认有时候会用justify-content: center或者其他对齐规则,导致和表头的左对齐不一致。用text-align: left加上!important(或者确保你的CSS优先级比默认样式高)就能轻松覆盖,让单元格和表头对齐统一。如果你的组件开了ViewEncapsulation,实在不行可以用::ng-deep来穿透样式,但优先推荐上面的类选择器方式,更干净。
内容的提问来源于stack exchange,提问作者Marcus Grass
相关产品推荐
相关产品推荐

