控制表格寬度是佈局常見需求。現代開發應棄用 HTML 屬性,全面擁抱 CSS 方案。
<!-- 不推薦 -->
<table width="400">
<tr>
<td width="100">A</td>
<td width="100">B</td>
<td width="100">C</td>
<td width="100">D</td>
</tr>
</table>
缺點:混合結構與表現、無響應式、維護困難、HTML5 標準不推薦。
table {
width: 100%; /* 填滿容器 */
width: 800px; /* 固定寬度 */
width: 50vw; /* 視窗百分比 */
max-width: 1200px; /* 最大限制 */
min-width: 300px; /* 最小限制 */
}
/* 固定像素 */
td:nth-child(1) { width: 100px; }
td:nth-child(2) { width: 200px; }
/* 百分比分配 (合計 100%) */
td.col-1 { width: 20%; }
td.col-2 { width: 30%; }
td.col-3 { width: 50%; }
/* 內容自適應 + 剩餘空間分配 */
td.fixed { width: 120px; }
td.auto { width: auto; } /* 瀏覽器自動分配剩餘空間 */
table {
table-layout: fixed; /* 關鍵:固定佈局算法 */
width: 100%;
}
table {
table-layout: auto; /* 預設:自動算法,根據內容計算 */
}
table-layout: fixed 優勢:
overflow: hidden、text-overflow: ellipsis 實現文字截斷.table-wrapper {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
table {
min-width: 600px; /* 觸發滾動的最小寬度 */
}
@media (max-width: 600px) {
table, thead, tbody, th, td, tr { display: block; }
thead { display: none; } /* 隱藏表頭,用 data-label 替代 */
td {
position: relative;
padding-left: 50%;
border: none;
border-bottom: 1px solid #eee;
}
td::before {
position: absolute;
left: 10px;
top: 50%;
transform: translateY(-50%);
content: attr(data-label);
font-weight: bold;
}
}
HTML 需添加 data-label 屬性:<td data-label="產品">...</td>
.table-container {
overflow-x: auto;
}
table {
width: max-content;
}
th:first-child, td:first-child {
position: sticky;
left: 0;
background: white;
z-index: 1;
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
}
| 現象 | 原因 | 解決 |
|---|---|---|
| 設寬度不生效 | table-layout:auto + 內容撐大 | 設 table-layout: fixed |
| 百分比寬度失效 | 父容器無寬度 | 父元素設定寬度或 width: 100% |
| 邊框導致寬度超出 | box-sizing: content-box (預設) | box-sizing: border-box 全域重置 |
| 合併儲存格寬度異常 | colspan 跨列計算複雜 | 用 <col> 定義欄寬、避免複雜合併 |
box-sizing: border-boxtable-layout: fixed + width: 100%<col style="width: 120px"> 定義overflow: hidden; text-overflow: ellipsis; white-space: nowrap<th scope="col|row">、<caption>、足夠對比度表格寬度控制核心在於 CSS table-layout: fixed 與響應式策略的結合,徹底拋棄 HTML width 屬性。