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

Angular 18 Mat-Table实现圆角与行悬停效果的正确方式

Angular Material 18.2.8 实现带圆角与行悬停的Mat-Table

核心思路

无需将表格设为透明,通过外层容器控制圆角范围,同时针对Mat-Table原生组件类设置行悬停样式,确保表头、数据行的样式完全适配圆角。

实现步骤

1. HTML结构(保持简洁嵌套)

<div class="table-card">
  <table mat-table [dataSource]="dataSource">
    <!-- 列定义示例 -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> 名称 </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>
    <!-- 其他列按需添加 -->
    
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</div>

2. 全局样式(styles.scss)

/* 外层卡片容器:控制圆角与溢出范围 */
.table-card {
  border-radius: 12px; /* 自定义圆角大小 */
  overflow: hidden; /* 关键:防止内部表格内容超出圆角边界 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 可选:添加阴影增强卡片质感 */
  margin: 16px;
}

/* 表格基础样式 */
.table-card mat-table {
  width: 100%;
  border-spacing: 0; /* 消除单元格间距 */
  border-collapse: separate; /* 避免合并边框导致圆角失效 */
}

/* 表头行样式 */
.table-card mat-header-row {
  background-color: #f5f5f5;
}

/* 数据行基础样式 */
.table-card mat-row {
  background-color: #ffffff;
  transition: background-color 0.2s ease; /* 悬停平滑过渡效果 */
}

/* 行悬停效果(覆盖表头与数据行) */
.table-card mat-header-row:hover,
.table-card mat-row:hover {
  background-color: #e8f0fe; /* 自定义悬停背景色 */
}

/* 适配圆角:表头首尾单元格 */
.table-card mat-header-cell:first-of-type {
  border-top-left-radius: 12px;
}
.table-card mat-header-cell:last-of-type {
  border-top-right-radius: 12px;
}

/* 适配圆角:最后一行数据的首尾单元格 */
.table-card mat-row:last-of-type mat-cell:first-of-type {
  border-bottom-left-radius: 12px;
}
.table-card mat-row:last-of-type mat-cell:last-of-type {
  border-bottom-right-radius: 12px;
}

/* 可选:调整单元格内边距 */
.table-card mat-header-cell,
.table-card mat-cell {
  padding: 12px 16px;
}

关键注意事项

  • overflow:hidden:必须给外层容器添加该属性,否则行背景会超出圆角范围,悬停效果出现露边问题。
  • 组件类优先级:直接使用mat-header-row和mat-row类设置样式,比原生tr优先级更高,确保悬停效果生效。
  • 边框设置:用border-spacing:0替代border-collapse:collapse,方便单独控制单元格的圆角样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:07:46