表格邊框與間距控制經歷從 HTML 屬性 (border, cellspacing, cellpadding) 到 CSS 完整接管的演進。理解兩種模型差異,能精準掌控表格視覺呈現。
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="200">1</td>
<td width="200">2</td>
<td width="200">3</td>
</tr>
<tr>
<td>a</td><td>b</td><td>c</td>
</tr>
<tr>
<td>中國</td><td>我</td><td>愛你</td>
</tr>
</table>
border="1":表格外框與儲存格邊框皆為 1px (雙重邊框)。cellspacing="0":儲存格間距為 0,**關鍵**——否預設 2px 產生雙線效果。cellpadding="0":儲存格內邊距 (內容到邊框) 為 0。<style>
.modern-table {
width: 100%;
border-collapse: collapse; /* 關鍵:合併邊框,等同 cellspacing="0" */
}
.modern-table th,
.modern-table td {
border: 1px solid #333; /* 統一邊框樣式 */
padding: 8px 12px; /* 等同 cellpadding */
text-align: left;
}
.modern-table th {
background: #f5f5f5;
font-weight: 600;
}
</style>
<table class="modern-table">
<thead>
<tr><th>編號</th><th>名稱</th><th>數量</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>產品 A</td><td>100</td></tr>
<tr><td>2</td><td>產品 B</td><td>200</td></tr>
</tbody>
</table>
| 特性 | 分離邊框模型 (預設 / border-collapse: separate) | 合併邊框模型 (border-collapse: collapse) |
|---|---|---|
| HTML 對應 | cellspacing="n" (預設 2px) | cellspacing="0" |
| 邊框關係 | 相鄰儲存格各有邊框,中間有間隙 | 相鄰儲存格共用單一邊框線 |
| 圓角支援 | 支援 border-radius (表格層級) | **不支援** border-radius (儲存格層級) |
| 邊框樣式衝突 | 無衝突,各自獨立 | 依優先順序決定:hidden > double > solid > dashed > dotted > ridge > outset > groove > inset > none |
| 效能 | 稍低 | 較高 |
<style>
/* 僅外框 */
.outer-border-only {
border-collapse: separate;
border-spacing: 0;
border: 2px solid #2c3e50;
}
.outer-border-only th,
.outer-border-only td {
border: none;
border-bottom: 1px solid #eee; /* 僅橫線 */
border-right: 1px solid #eee; /* 僅直線 */
}
.outer-border-only tr:last-child td { border-bottom: none; }
.outer-border-only tr td:last-child { border-right: none; }
/* 斑馬紋 */
.zebra tbody tr:nth-child(even) { background: #f9f9f9; }
/* 懸浮高亮 */
.hover-highlight tbody tr:hover { background: #e8f4fd; }
</style>
border-collapse: collapse,簡潔、效能佳、易控制。border-collapse: separate + border-spacing: 0 + border-radius 於 <table>。nth-child、:hover 提升可讀性與互動體驗。CSS 完全接管表格樣式,是現代前端開發的基本功。