萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML 表格固定寬高與內容截斷:table-layout:fixed、overflow 隱藏、文字省略號、響應式最佳實踐

強制表格尺寸不再靠死背:table-layout: fixed + CSS 截斷三部曲

預設 table-layout: auto 會根據內容計算欄寬,導致版面不穩。table-layout: fixed 讓欄寬由 <col> 或首列 <th> 寬度決定,內容超出不再撐大表格,配合 overflow、text-overflow 實現穩定佈局。

核心 CSS 組合拳

.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%; }

HTML 結構配合 <colgroup>

<table class="table-fixed">
  <colgroup>
    <col style="width: 30%;">
    <col style="width: 50%;">
    <col style="width: 20%;">
  </colgroup>
  <thead>...</thead>
  <tbody>...</tbody>
</table>

使用 <col> 定義寬度語意更清晰,且不受首列內容影響。

進階:單元格內容工具提示 (Tooltip)

<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 完整顯示
  • 匯出 Excel/CSV 時使用原始資料,而非截斷後的 DOM 文字

避坑指南

  1. 忘記 table-layout: fixed → 寬度設定不生效,內容仍撐大
  2. 未設定 overflow: hidden → 內容溢出相鄰儲存格
  3. 對 tr 設定寬度 → 無效,必須對 col、th、td
  4. 合併儲存格 (colspan/rowspan) 配合 fixed → 需在 col 定義總寬度,合併儲存格寬度自動合併
copyright © 萬盛學電腦網 all rights reserved