表格邊框不只是簡單的線條,透過 border-collapse、border-spacing、CSS 邊框模型,能創造豐富的視覺效果。
| 特性 | separate (預設)
| collapse
|
|---|---|---|
| 邊框關係 | 各儲存格獨立邊框 | 相鄰儲存格共用邊框 |
| 間距控制 | border-spacing |
無間距(或 0) |
| 圓角支援 | ✅ 表格可圓角 | ❌ 表格無圓角 |
| 雙線問題 | 有(需 spacing=0) | 無(單線) |
| 邊框衝突規則 | 無 | 有優先級算法 |
| 效能 | 稍慢 | 較快 |
.table-separate {
border-collapse: separate;
border-spacing: 8px 4px; /* 水平 垂直 */
border-radius: 12px; /* 表格整體圓角 */
overflow: hidden; /* 裁切內容圓角 */
background: #fff;
}
.table-separate th,
.table-separate td {
border: 2px solid #e0e0e0;
border-radius: 8px; /* 儲存格個別圓角 */
padding: 12px 16px;
background: #fafafa;
}
/* 首列/末列圓角優化 */
.table-separate tr:first-child th:first-child { border-top-left-radius: 8px; }
.table-separate tr:first-child th:last-child { border-top-right-radius: 8px; }
.table-separate tr:last-child td:first-child { border-bottom-left-radius: 8px; }
.table-separate tr:last-child td:last-child { border-bottom-right-radius: 8px; }
當相鄰儲存格邊框不同時,瀏覽器按優先級選擇顯示:
hidden > 所有(隱藏邊框)double > solid > dashed > dotted > ridge > outset > groove > inset > none.table-collapse {
border-collapse: collapse;
border: 2px solid #336699; /* 表格外框 */
}
.table-collapse th {
border: 1px solid #336699;
background: #336699;
color: white;
}
.table-collapse td {
border: 1px solid #ddd;
}
/* 隱藏特定內部邊框 */
.table-collapse tr:first-child td { border-top: hidden; }
.table-collapse td:first-child { border-left: hidden; }
.table-minimal {
border-collapse: collapse;
border-bottom: 1px solid #000;
}
.table-minimal th,
.table-minimal td {
border: none;
border-bottom: 1px solid #eee;
padding: 12px 0;
}
.table-minimal thead th {
border-bottom: 2px solid #000;
font-weight: 600;
}
.table-card {
border-collapse: separate;
border-spacing: 0 12px;
}
.table-card tbody {
display: table-row-group; /* 修正 Firefox bug */
}
.table-card tr {
background: white;
box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}
.table-card td:first-child { border-radius: 8px 0 0 8px; }
.table-card td:last-child { border-radius: 0 8px 8px 0; }
.table-grid {
border-collapse: collapse;
}
.table-grid td {
border: 1px solid #e0e0e0;
transition: background 0.2s;
}
.table-grid tbody tr:hover td {
background: #fffbe6;
border-color: #faad14;
}
@media print {
.table-print {
border-collapse: collapse;
page-break-inside: auto;
}
.table-print tr {
page-break-inside: avoid;
page-break-after: auto;
}
.table-print thead {
display: table-header-group; /* 每頁重複表頭 */
}
.table-print tfoot {
display: table-footer-group;
}
.table-print td {
border: 1px solid #999 !important;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}
/* 開發時快速可視化所有邊框 */
* { outline: 1px solid red; }
/* 或只針對表格 */
table, th, td { outline: 1px dashed rgba(255,0,0,0.5); }
理解邊框模型機制,能精準控制每一條線的呈現。