傳統 HTML 屬性 vs CSS
| HTML 屬性 | CSS 替代方案 | 說明 |
cellpadding="0" | td, th { padding: 0; } | 單元格內邊距 |
cellspacing="0" | table { border-collapse: collapse; } | 單元格間距/邊框合併 |
border-collapse 詳細解析
table {
border-collapse: collapse; /* 合併邊框模型 */
/* border-collapse: separate; */ /* 分離邊框模型(預設) */
/* border-spacing: 0; */ /* 僅在 separate 時生效,等同 cellspacing="0" */
}
兩種邊框模型對比
| 特性 | collapse (合併) | separate (分離,預設) |
| 相鄰單元格邊框 | 合併為單條(取較粗/樣式優先級) | 各自獨立,雙線 |
| cellspacing 效果 | 無效(忽略) | 由 border-spacing 控制 |
| border-radius | ❌ 不生效(邊框合併無圓角) | ✅ 生效 |
| 邊框樣式優先級 | hidden > double > solid > dashed > dotted > none > inset > outset | 各自獨立 |
| 性能 | 渲染較快 | 稍慢 |
實戰最佳實踐
/***** 現代表格重置基礎樣式 *****/
.table {
width: 100%;
border-collapse: collapse; /* 核心:合併邊框,替代 cellspacing=0 */
font-variant-numeric: tabular-nums; /* 數字等寬對齊 */
}
.table th,
.table td {
padding: 12px 16px; /* 替代 cellpadding,可自定義 */
border: 1px solid #e5e7eb; /* 統一邊框 */
text-align: left;
vertical-align: middle;
}
.table thead th {
background: #f9fafb;
font-weight: 600;
color: #374151;
white-space: nowrap;
}
.table tbody tr:hover {
background: #f9fafb;
}
/***** 需要圓角表格時:必須用 separate + 邊框技巧 *****/
.table-rounded {
border-collapse: separate;
border-spacing: 0;
border-radius: 8px;
overflow: hidden; /* 裁剪內部圓角 */
}
.table-rounded th,
.table-rounded td {
border: none;
border-bottom: 1px solid #e5e7eb;
border-right: 1px solid #e5e7eb;
}
.table-rounded th:last-child,
.table-rounded td:last-child {
border-right: none;
}
.table-rounded tbody tr:last-child td {
border-bottom: none;
}
常見誤區
- ❌ 同時設定
border-collapse: collapse 和 border-spacing → spacing 無效
- ❌ 想要圓角表格卻用
collapse → 必須用 separate + overflow: hidden
- ❌
cellpadding="10" 對應 padding: 10px,但 CSS 可分四向控制(更靈活)
總結
標準現代寫法:table { border-collapse: collapse; } + td, th { padding: ...; }
完全替代 cellspacing="0" cellpadding="0",且控制力更強、語義分離更好。