| 時代 | 方法 | 範例 | 缺點 |
|---|---|---|---|
| HTML 4 / 早期 | 屬性 width | <table width="400"> | 混雜表現與結構、難維護、無響應式 |
| CSS 2.1 | table { width: ... } | table { width: 100%; } | 需搭配 table-layout 控制演算法 |
| 現代 RWD | CSS + 媒體查詢 + 容器查詢 | max-width: 100%; overflow-x: auto; | 需處理小螢幕可用性 |
table {
width: 100%; /* 撐滿容器 */
max-width: 800px; /* 最大寬度限制 */
table-layout: fixed; /* 關鍵:固定佈局演算法,速度快、可控 */
}
th, td {
width: 25%; /* 僅在 fixed 生效時精確分配 */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
table-layout: fixed 讓瀏覽器依 <col> 或第一列寬度直接計算,不需分析所有儲存格內容,大幅提升大型表格渲染速度。
<table>
<colgroup>
<col style="width: 50px;"> <!-- 固定 50px -->
<col style="width: 30%;"> <!-- 30% -->
<col style="width: 1fr;"> <-- 剩餘空間 (需 fixed) -->
<col span="2" style="width: auto;"> <-- 兩欄自動 -->
</colgroup>
<thead>...</thead>
<tbody>...</tbody>
</table>
.table-wrapper { overflow-x: auto; -webkit-overflow-scrolling: touch; }
table { min-width: 600px; } /* 強制最小寬,觸發捲動 */
th:first-child, td:first-child {
position: sticky; left: 0; background: #fff; z-index: 1;
}
@media (max-width: 600px) {
table, thead, tbody, th, td, tr { display: block; }
thead { display: none; } /* 隱藏表頭,改用 data-label */
td { display: flex; justify-content: space-between; padding: .5rem; border-bottom: 1px solid #eee; }
td::before { content: attr(data-label); font-weight: bold; }
}
<td data-label="Price">$99</td>
<td> 直接設 width 卻未設 table-layout: fixed → 瀏覽器會自動調整,結果不可預期。border-collapse: collapse 會合併邊框,寬度計算不含邊框;separate 則含邊框。-webkit-overflow-scrolling: touch 體驗順滑。