預設 table-layout: auto 會根據內容計算欄寬,導致版面不穩。table-layout: fixed 讓欄寬由 <col> 或首列 <th> 寬度決定,內容超出不再撐大表格,配合 overflow、text-overflow 實現穩定佈局。
.table-fixed {
table-layout: fixed; /* 關鍵:鎖定欄寬演算法 */
width: 100%; /* 表格佔滿容器 */
border-collapse: collapse;
}
.table-fixed col,
.table-fixed th,
.table-fixed td {
overflow: hidden; /* 隱藏超出內容 */
white-space: nowrap; /* 強制單行 */
text-overflow: ellipsis; /* 省略號 */
/* 或換行截斷:
white-space: normal;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
*/
}
.table-fixed th:nth-child(1), .table-fixed td:nth-child(1) { width: 30%; }
.table-fixed th:nth-child(2), .table-fixed td:nth-child(2) { width: 50%; }
.table-fixed th:nth-child(3), .table-fixed td:nth-child(3) { width: 20%; }
<table class="table-fixed">
<colgroup>
<col style="width: 30%;">
<col style="width: 50%;">
<col style="width: 20%;">
</colgroup>
<thead>...</thead>
<tbody>...</tbody>
</table>
使用 <col> 定義寬度語意更清晰,且不受首列內容影響。
<td class="ellipsis" title="完整的長文字內容">長文字會被截斷...</td>
<style>
.ellipsis {
overflow: hidden; white-space: nowrap; text-overflow: ellipsis;
max-width: 100%; /* 確保在 fixed 表格生效 */
}
.ellipsis:hover::after {
content: attr(title);
position: absolute; z-index: 10;
background: #333; color: #fff; padding: 4px 8px;
border-radius: 4px; font-size: 0.875rem; white-space: normal;
max-width: 300px; top: 100%; left: 0;
}
</style>
.table-wrapper { overflow-x: auto; }
.table-fixed {
min-width: 800px; /* 關鍵欄總寬度下限 */
}
@media (max-width: 600px) {
.table-fixed th:nth-child(1),
.table-fixed td:nth-child(1) {
position: sticky; left: 0; background: #fff; z-index: 1;
}
}
text-overflow: ellipsis,改用 white-space: normal 完整顯示table-layout: fixed → 寬度設定不生效,內容仍撐大overflow: hidden → 內容溢出相鄰儲存格tr 設定寬度 → 無效,必須對 col、th、tdcol 定義總寬度,合併儲存格寬度自動合併