我正在开发一个带有垫子表的 Angular 应用程序。我想让表格可以通过粘性标题滚动。但是,滚动条似乎出现在表格之外。
我尝试使用具有高度和溢出属性的容器,但无法成功将滚动条放置在表格内。与 ngx-scrollbar 和 perfect-scrollbar 等 npm 包的结果相同。
有没有办法使用纯CSS设置表格内的滚动条?
使用
flexbox
涉及很多更改,我不能保证它是所有场景的最佳解决方案,但您可以使用桌子上的display:flex
并在桌子上的overflow-y: scroll
上设置tbody
来实现!
CSS
/* Add application styles & imports to this file! */
@import 'node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css';
.my-table {
overflow: hidden !important;
}
.my-table table[mat-table] {
overflow: hidden;
display: flex !important;
flex-direction: column;
}
.my-table table[mat-table] {
overflow: hidden;
display: flex !important;
flex-direction: column;
height: inherit;
}
.my-table table[mat-table] thead tr {
display: flex;
align-items: center;
justify-content: center;
}
.my-table table[mat-table] thead tr th {
display: flex;
flex: 1;
height: 100%;
align-items: center;
justify-content: center;
}
.my-table table[mat-table] tbody {
overflow-y: scroll !important;
}
.my-table table[mat-table] tbody tr {
display: flex;
align-items: center;
justify-content: center;
}
.my-table table[mat-table] tbody tr td {
display: flex;
flex: 1;
height: 100%;
align-items: center;
justify-content: center;
}
html
<div class="my-table">
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->
<!-- Position Column -->
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef>No.</th>
<td mat-cell *matCellDef="let element">{{ element.position }}</td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>Name</th>
<td mat-cell *matCellDef="let element">{{ element.name }}</td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="weight">
<th mat-header-cell *matHeaderCellDef>Weight</th>
<td mat-cell *matCellDef="let element">{{ element.weight }}</td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="symbol">
<th mat-header-cell *matHeaderCellDef>Symbol</th>
<td mat-cell *matCellDef="let element">{{ element.symbol }}</td>
</ng-container>
<tr
mat-header-row
*matHeaderRowDef="displayedColumns; sticky: true"
style="#A8ACAA"
></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
</div>