控制表格與儲存格寬度,早期使用 HTML 屬性 (width),現代開發全面改用 CSS。本文對比兩種做法並說明最佳實務。
<table width="400">
<tr>
<td width="100">欄位 1</td>
<td width="100">欄位 2</td>
<td width="100">欄位 3</td>
<td width="100">欄位 4</td>
</tr>
</table>
table width:設定整體表格寬度 (像素或百分比)。td width:設定該欄寬度,總和建議等於 table width。<style>
.data-table {
width: 100%; /* 響應式:滿版寬度 */
max-width: 800px; /* 最大寬度限制 */
margin: 0 auto; /* 水平置中 */
border-collapse: collapse; /* 合併邊框 */
}
.data-table th,
.data-table td {
padding: 12px 16px;
border: 1px solid #ddd;
text-align: left;
}
/* 指定特定欄寬度 */
.data-table th:nth-child(1),
.data-table td:nth-child(1) { width: 15%; } /* 第一欄 15% */
.data-table th:nth-child(2),
.data-table td:nth-child(2) { width: 35%; } /* 第二欄 35% */
.data-table th:nth-child(3),
.data-table td:nth-child(3) { width: 25%; } /* 第三欄 25% */
.data-table th:nth-child(4),
.data-table td:nth-child(4) { width: 25%; } /* 第四欄 25% */
</style>
<table class="data-table">
<thead>
<tr><th>產品</th><th>說明</th><th>價格</th><th>庫存</th></tr>
</thead>
<tbody>
<tr><td>筆電</td><td>高效能輕薄筆電</td><td>$35,000</td><td>12</td></tr>
<tr><td>滑鼠</td><td>無線靜音滑鼠</td><td>$590</td><td>56</td></tr>
</tbody>
</table>
| 單位 | 適用場景 | 範例 |
|---|---|---|
% | 響應式欄寬,隨容器彈性調整 | width: 25%; |
px | 固定寬度欄位 (如圖示欄、操作欄) | width: 48px; |
em/rem | 相對字體大小,適合文字欄 | width: 20em; |
fr (Grid) | CSS Grid 分配剩餘空間 | grid-template-columns: 1fr 2fr 1fr; |
min-content | 最小內容寬度 | width: min-content; |
max-content | 最大內容寬度 (不換行) | width: max-content; |
fit-content() | 夾在 min/max 之間 | width: fit-content(300px); |
table {
table-layout: fixed; /* 關鍵:固定佈局演算法 */
width: 100%;
}
/* fixed 模式下,瀏覽器依第一列 (或 colgroup) 寬度快速計算,
不會因內容過長撐大欄位,效能更好、版面更穩定 */
搭配 table-layout: fixed 與 overflow: hidden、text-overflow: ellipsis,可完美控制長文字截斷顯示。
table-layout: fixed 獲得穩定、高效能渲染。<th scope="col">、<caption>、<thead>/<tbody>。