Table 布局雖被詬病,但語義化 Table 在數據展示、表單對齊等場景仍是最佳選擇。關鍵在於「最大程度分離樣式與結構」。本文示範如何利用 <thead>、<tbody>、<tfoot>、<colgroup>、<col> 等原生屬性,配合 CSS 實現零內聯樣式的複雜表格。

<table id="itab">
<caption>最大限度分離 Table 樣式與結構</caption>
<colgroup>
<col class="linenum">
<col class="id-1">
<col class="id-2">
<col class="id-3">
</colgroup>
<thead>
<tr><th>LINENUM</th><th>ID-1</th><th>ID-2</th><th>ID-3</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>A</td><td>CY</td><td>I</td></tr>
<tr><td>2</td><td>Br</td><td>S</td><td>KMQ</td></tr>
<tr><td>3</td><td>HTC</td><td>LLI</td><td>P</td></tr>
<tr><td>4</td><td>ACC</td><td>G</td><td>QO</td></tr>
<tr><td>5</td><td>Z</td><td>AHD</td><td>M</td></tr>
</tbody>
<tfoot>
<tr><th>LINE.NO</th><th>ID-1</th><th>ID-2</th><th>ID-3</th></tr>
</tfoot>
</table>
table#itab { border-collapse: collapse; border: 1px solid #999; width: 50em; margin: 0 auto; }
#itab caption { font-size: 1em; font-weight: normal; color: #a40000; }
#itab thead { background: #ffc; }
#itab td, #itab th { border: 1px solid #ccc; }
#itab td { padding-left: 0.8em; }
#itab tfoot { background: #fcc; }
#itab .linenum { width: 15%; background: #0cf; }
#itab .id-1 { width: 20%; background: #cf9; }
#itab .id-2 { width: 25%; background: #eee; }
#itab .id-3 { width: 30%; background: #9ff; }
col 僅支援寬度、背景、邊框等少數屬性,不支援字體顏色、對齊(除 IE6 外)。需配合 :first-child 等高級選擇器處理非 IE 瀏覽器。thead、tbody、tfoot 天然承載表頭、主體、表尾樣式,結構清晰。HTML 每個標籖都有特定功能,如同身體器官。善用 table 族群語義屬性,配合 CSS 與 JS 分工協作,才能寫出可維護、高性能、語義化的表格頁面。