表格並不是「不能用」,而是常被用得很隨便。與其套一堆行內屬性,不如把結構寫清楚,外觀全部交給 CSS。以下用一張歷史人物對照表做示範。
<body>
<table class="tableList" width="600" cellspacing="0">
<caption>江山代有才人出 各領風騷數百年</caption>
<thead>
<tr>
<th>三代</th><th>漢朝</th><th>晉朝</th><th>唐朝</th><th>宋朝</th><th>明朝</th>
</tr>
</thead>
<tbody>
<tr>
<td>孔子</td><td>董仲舒</td><td>阮籍</td><td>李白</td><td>蘇軾</td><td>王陽明</td>
</tr>
<tr class="odd">
<td>孟子</td><td>東方朔</td><td>嵇康</td><td>杜甫</td><td>辛棄疾</td><td>唐寅</td>
</tr>
<tr>
<td>老子</td><td>揚雄</td><td>陶淵明</td><td>李商隱</td><td>陸游</td><td>徐渭</td>
</tr>
<tr class="odd">
<td>莊子</td><td>左思</td><td>王羲之</td><td>李賀</td><td>范仲淹</td><td>楊慎</td>
</tr>
</tbody>
</table>
</body>
/* 表格外框:上下有粗線,左右留空 */
table.tableList {
border-top: 1px solid #000000;
border-bottom: 1px solid #000000;
}
/* 標題(caption) */
table.tableList caption {
font-size: 16px;
font-weight: bold;
}
/* 表頭列:高度、底紋、分隔線 */
table.tableList thead {
height: 31px;
background: #ffffff url(../img/th_flower_bg.gif) repeat-x left center;
border-top: 1px solid #e0dace;
border-bottom: 1px solid #e0dace;
}
/* 表格主體 */
table.tableList tbody {
height: 25px;
}
/* 欄位標題 */
table.tableList th {
border-bottom: 1px solid #e0dace;
text-align: center;
}
/* 隔行變色 */
table.tableList tr.odd {
background-color: #faf4e8;
}
/* 資料格 */
table.tableList td {
border-bottom: 1px solid #e0dace;
padding: 4px 4px 1px;
text-align: left;
}
用 caption 而非標題段落。 <caption> 語意上就是「這張表的名稱」,螢幕閱讀器會主動朗讀,這是用 <h3> 湊不出來的效果。
隔行變色不必靠後端。 上面用 class="odd" 手工標記,若不想動 HTML,改用 tr:nth-child(even) { background-color: #faf4e8 } 就能自動處理,還少寫一堆 class。
border-collapse 值得加上。 相鄰儲存格的邊框預設是分開的,加 border-collapse: collapse 可以合併成單線,做出乾淨的表格線。
記得補 scope。 為 <th> 加上 scope="col" 或 scope="row",能讓輔助工具正確理解標題與資料的對應關係,成本極低但意義重大。