<table> 定義表格,內含 <caption>、<thead>、<tbody>、<tfoot>、<tr>、<th>、<td>。HTML5 已移除 border、bgcolor、background 等表現屬性,全面改用 CSS。
| 屬性 | 作用對象 | 範例 |
|---|---|---|
| background-color | 整張表、列、儲存格 | table { background:#f9f9f9; } |
| color | 文字顏色 | th { color:#fff; } |
| border-color | 邊框顏色 | td { border:1px solid #ddd; } |
| border-collapse | 合併邊框模式 | table { border-collapse:collapse; }(必要) |
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #dee2e6; padding: 12px 16px; text-align: left; }
th { background: #343a40; color: #fff; }
tbody tr:nth-child(even) { background: #f8f9fa; }
tbody tr:hover { background: #e2e6ea; }
td.status-success { background: #d4edda; color: #155724; }
td.status-warning { background: #fff3cd; color: #856404; }
td.status-danger { background: #f8d7da; color: #721c24; }
col:nth-child(1) { background: #f0f4f8; } /* 第一欄淡藍 */
col:nth-child(3) { background: #fff8e1; } /* 第三欄淡黃 */
需在 <table> 內宣告 <colgroup><col><col><col></colgroup> 讓 col 選擇器生效。
<table border="1" bgcolor="#f0f0f0">
<tr bgcolor="#333"><th><font color="white">標題</font></th></tr>
<tr><td bgcolor="#fff">資料</td></tr>
</table>
強烈不建議在新專案使用,維護困難、無法響應式、違反關注點分離。
<th scope="col|row"> 標示表頭範圍,輔助閱讀器導航。<caption> 提供表格標題,置於 <table> 直後。.table-responsive { overflow-x: auto; -webkit-overflow-scrolling: touch; }
/* 或將表格在小螢幕轉為卡片式 */
@media (max-width: 600px) {
table, thead, tbody, th, td, tr { display: block; }
thead { position: absolute; top: -9999px; left: -9999px; }
tr { border: 1px solid #ddd; margin-bottom: 1rem; }
td { border: none; border-bottom: 1px solid #eee; position: relative; padding-left: 50%; }
td::before { content: attr(data-label); position: absolute; left: 1rem; font-weight: bold; }
}
配合 HTML <td data-label="欄位名"> 實現無障礙卡片視圖。