``| 無需 CSS、舊瀏覽器相容 | 混雜表現與結構、難維護、無響應式 | ⭐ 僅維護舊專案 |
| CSS `width` | `table { width: 100%; }` | 關注點分離、支援單位多樣、可媒體查詢 | 需額外 CSS | ⭐⭐⭐ 標準做法 |
| CSS `table-layout` | `table { table-layout: fixed; width: 100%; }` | 渲染快、寬度固定、配合 `overflow` 截斷 | 內容超寬需自行處理 | ⭐⭐⭐⭐ 大量資料/固定版面 |
核心 CSS 寬度單位與場景
/* 1. 百分比:響應式佔滿容器 */
table { width: 100%; }
/* 2. 固定像素:精確控制(列印、郵件模板) */
table { width: 800px; }
/* 3. 視窗單位:全螢幕表格 */
table { width: 90vw; max-width: 1200px; }
/* 4. 內容自適應(預設 auto) */
table { width: auto; } /* 依內容撐開 */
/* 5. min/max 限制範圍 */
table { width: 100%; min-width: 600px; max-width: 1200px; }
欄位寬度控制策略
自動分配(預設 `table-layout: auto`)
瀏覽器依內容計算各欄寬度,內容長則欄寬大。
固定佈局 `table-layout: fixed`(高效能、可控)
table {
table-layout: fixed;
width: 100%;
}
th:nth-child(1), td:nth-child(1) { width: 30%; } /* 第一欄 30% */
th:nth-child(2), td:nth-child(2) { width: 50%; } /* 第二欄 50% */
th:nth-child(3), td:nth-child(3) { width: 20%; } /* 第三欄 20% */
**優點**:只讀第一行即決定寬度,渲染極快;欄寬不受內容影響。
內容溢位處理:防止撐破版面
文字截斷省略號(單行)
td {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 200px; /* 配合 fixed layout 或 max-width */
}
長英文/網址強制換行
td {
word-wrap: break-word; /* 舊屬性名,相容性佳 */
overflow-wrap: break-word; /* 新標準屬性 */
word-break: break-all; /* 中文斷字更激進 */
}
保留空白與換行(程式碼、日誌)
td.code {
white-space: pre-wrap; /* 保留空白並自動換行 */
font-family: monospace;
}
響應式表格三大模式
1. 水平捲動(最簡單,資料完整)
.table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }
table { min-width: 600px; } /* 強制最小寬觸發捲動 */
2. 欄位疊放(卡片模式,行動優先)
@media (max-width: 600px) {
table, thead, tbody, th, td, tr { display: block; width: 100%; }
thead { display: none; } /* 隱藏表頭,改用 data-label */
td {
display: flex; justify-content: space-between; padding: 0.5rem;
border-bottom: 1px solid #eee;
}
td::before { content: attr(data-label); font-weight: bold; }
}
/* HTML 需加 data-label */
<td data-label="營收">$1,200</td>
3. 關鍵欄固定,其餘捲動(進階)
th:first-child, td:first-child {
position: sticky; left: 0; background: white; z-index: 1;
box-shadow: 2px 0 4px rgba(0,0,0,0.1);
}
常見問題排查
| 現象 | 原因 | 解決 |
| 設定 `width: 100%` 但表格不滿容器 | 父容器無寬度、或 `display: inline-table` | 父層給寬度、或 `table { display: table; width: 100%; }` |
| 欄寬不如預期 | `table-layout: auto` 且內容過長 | 改 `fixed`、加 `min-width`、`overflow` 處理 |
| 合併儲存格後寬度錯亂 | `colspan` 影響計算 | 用 `` 明確定義 |
最佳實踐清單
- 預設用 `table { width: 100%; table-layout: fixed; }`。
- 用 `` 定義欄寬,語意清晰且不受內容干擾。
- 文字欄位加 `overflow-wrap: break-word` 防撐破。
- 行動裝置套用卡片模式或水平捲動。
- 大量資料(>1000 列)考慮虛擬滾動或分頁,避免 DOM 過大。
copyright © 萬盛學電腦網 all rights reserved
|