萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML 表格顏色設定完全指南:從屬性到 CSS 最佳實踐

<table> 標籤回顧

<table> 定義表格,內含 <caption>、<thead>、<tbody>、<tfoot>、<tr>、<th>、<td>。HTML5 已移除 border、bgcolor、background 等表現屬性,全面改用 CSS。

CSS 控制表格顏色核心屬性

屬性作用對象範例
background-color整張表、列、儲存格table { background:#f9f9f9; }
color文字顏色th { color:#fff; }
border-color邊框顏色td { border:1px solid #ddd; }
border-collapse合併邊框模式table { border-collapse:collapse; }(必要)

常見配色模式範例

1. 表頭深色、內容斑馬紋

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; }

2. 條件列高亮(如狀態欄)

td.status-success { background: #d4edda; color: #155724; }
td.status-warning { background: #fff3cd; color: #856404; }
td.status-danger  { background: #f8d7da; color: #721c24; }

3. 列背景色區分

col:nth-child(1) { background: #f0f4f8; }  /* 第一欄淡藍 */
col:nth-child(3) { background: #fff8e1; }  /* 第三欄淡黃 */

需在 <table> 內宣告 <colgroup><col><col><col></colgroup> 讓 col 選擇器生效。

HTML 屬性寫法(僅供維護舊專案參考)

<table border="1" bgcolor="#f0f0f0">
  <tr bgcolor="#333"><th><font color="white">標題</font></th></tr>
  <tr><td bgcolor="#fff">資料</td></tr>
</table>

強烈不建議在新專案使用,維護困難、無法響應式、違反關注點分離。

無障礙與可用性提醒

  • 確保文字與背景對比度達 WCAG AA (4.5:1) 或 AAA (7:1)。
  • 不要單靠顏色傳達資訊(如紅色表錯誤),需配合圖示/文字。
  • <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="欄位名"> 實現無障礙卡片視圖。

copyright © 萬盛學電腦網 all rights reserved