表格寬度控制涉及 HTML 屬性、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>
缺點:混雜表現與結構、無響應式能力、難維護。
<style>
.table-fixed {
width: 100%; /* 容器寬度 */
table-layout: fixed; /* 關鍵:固定佈局算法 */
border-collapse: collapse;
}
.table-fixed th,
.table-fixed td {
width: 25%; /* 百分比分配 */
padding: 12px 8px;
border: 1px solid #ddd;
overflow: hidden; /* 防內容撐開 */
text-overflow: ellipsis;
white-space: nowrap;
}
/* 固定像素寬度欄位 */
.col-id { width: 60px; }
.col-name { width: 200px; }
.col-desc { width: auto; } /* 剩餘空間 */
</style>
<table class="table-fixed">
<colgroup>
<col class="col-id">
<col class="col-name">
<col class="col-desc">
</colgroup>
<thead>...</thead>
<tbody>...</tbody>
</table>
| 特性 | auto (預設) |
fixed |
|---|---|---|
| 計算基準 | 內容寬度 | 表格/列寬度設定 |
| 渲染速度 | 較慢(需分析所有內容) | 極快(首行決定) |
| 寬度可控性 | 低(內容撐開) | 高(嚴格遵守設定) |
| 溢出處理 | 自動擴展 | 需配合 overflow |
| 適用場景 | 內容不固定、小型表格 | 大數據、固定佈局、高效能 |
.table-responsive {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
<div class="table-responsive">
<table>...</table>
</div>
.table-sticky {
overflow-x: auto;
}
.table-sticky th:first-child,
.table-sticky td:first-child {
position: sticky;
left: 0;
background: white;
z-index: 1;
box-shadow: 2px 0 4px rgba(0,0,0,0.1);
}
@media (max-width: 640px) {
.table-card thead { display: none; }
.table-card tbody tr {
display: block;
border: 1px solid #ddd;
margin-bottom: 1rem;
padding: 1rem;
}
.table-card td {
display: flex;
justify-content: space-between;
padding: 0.5rem 0;
border-bottom: 1px solid #eee;
}
.table-card td::before {
content: attr(data-label);
font-weight: bold;
}
}
/* HTML 需加 data-label */
<td data-label="姓名">張三</td>
| 問題 | 原因 | 解決 |
|---|---|---|
| 設寬度無效 | table-layout: auto + 內容過長 | 改用 fixed + overflow |
| 欄位不平均 | 未設 colgroup/width | 用 col 定義或 th 設 width |
| 手機橫向滾動卡頓 | 缺 -webkit-overflow-scrolling | 加 touch 滾動優化 |
| 列印截斷 | overflow: hidden | @media print 重置 overflow |
選對佈局算法、善用 colgroup、配合響應式策略,表格寬度不再是難題。