預設下,HTML 表格會根據內容自動調整欄寬 (auto layout),導致版面不穩定。使用 CSS table-layout: fixed 可強制表格依據預設寬度渲染,大幅提升渲染效能與版面可預測性。
<style>
.fixed-table {
width: 300px; /* 表格固定總寬 */
border: 0; /* 移除預設邊框 */
border-collapse: collapse; /* 合併邊框 */
table-layout: fixed; /* 關鍵:固定佈局模式 */
}
.fixed-table td {
border: 1px solid #ccc; /* 儲存格邊框 */
padding: 8px;
overflow: hidden; * 隱藏超出內容 */
text-overflow: ellipsis; * 超出顯示省略號 */
white-space: nowrap; * 強制不換行 */
}
</style>
<table class="fixed-table">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
| 特性 | auto (預設) | fixed |
|---|---|---|
| 演算法 | 分析所有儲存格內容再計算寬度 | 僅依第一列 (或 <col>) 寬度計算 |
| 渲染速度 | 較慢 (大表格明顯) | 極快,適合大量資料 |
| 寬度穩定性 | 內容撐開,版面易破裂 | 嚴格遵守設定寬度 |
| 內容溢出處理 | 自動換行或撐大 | 需搭配 overflow 處理 |
| 適用場景 | 簡單、內容不可預測的小表格 | 大型資料表、固定版面、效能敏感 |
<table class="fixed-table">
<colgroup>
<col style="width: 50px;"> <!-- 固定 50px -->
<col style="width: 1fr;"> <!-- 剩餘空間彈性分配 (需 Grid 支援) -->
<col style="width: 20%;"> <!-- 百分比 -->
<col style="width: 100px;"> <!-- 固定 100px -->
</colgroup>
<thead>
<tr><th>ID</th><th>名稱</th><th>比例</th><th>操作</th></tr>
</thead>
<tbody>...</tbody>
</table>
搭配 <col> 可在不修改 <td> 的情況下集中管理欄寬,維護性極佳。
<div class="table-wrapper" style="height: 300px; overflow-y: auto;">
<table class="fixed-table">
<colgroup>
<col style="width: 60px;">
<col style="width: 200px;">
<col style="width: 1fr;">
</colgroup>
<thead>
<tr><th>編號</th><th>商品名稱</th><th>詳細說明</th></tr>
</thead>
<tbody>
<tr><td>001</td><td>超長商品名稱會自動截斷顯示省略號</td><td>這裡是很長的說明文字...</td></tr>
<!-- 更多列 -->
</tbody>
</table>
</div>
掌握 table-layout: fixed 讓表格版面不再崩壞,是處理大量表格資料的關鍵技能。