萬盛學電腦網

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

HTML 表格自動換行與內容溢出處理:white-space、word-break、overflow 完整解析

核心問題:表格儲存格預設不換行

瀏覽器預設 white-space: nowrap 行為讓儲存格內容**單行顯示**,超出寬度會**撐開欄位** (若 table-layout: auto) 或 **溢出隱藏/顯示** (若 table-layout: fixed),導致版面崩壞或內容無法閱讀。

CSS 關鍵屬性組合拳

屬性關鍵值效果適用場景
white-spacenormal (預設)合併空白、自動換行一般文字段落
nowrap**強制不換行**,合併空白單行標題、代碼、配合 ellipsis 截斷
pre-wrap保留空白與換行符、自動換行程式碼區塊、預設格式文字
word-breaknormal (預設)依語言規則斷行 (中文自動斷行,英文單字不斷)一般中文內容
break-all**任意字元處斷行** (英文單字中間也會斷)長串無空格代碼、哈希值、網址防撐破
keep-all中日韓文字**不斷行** (視同英文單字)不想讓中文句子被強制拆分
overflow-wrap (word-wrap)break-word**單字過長無法放入時才在邊界斷行** (較溫和,不拆短單字)**推薦通用設定**,文章、使用者輸入、混合語言內容
overflowhidden截斷超出內容配合 text-overflow: ellipsis 顯示省略號
auto / scroll出現捲軸單儲存格滾動、代碼區塊

三大典型場景解決方案

場景一:單行截斷顯示省略號 (最常見需求)

.cell-ellipsis {
  white-space: nowrap;       /* 1. 強制不換行 */
  overflow: hidden;          /* 2. 隱藏溢出 */
  text-overflow: ellipsis;   /* 3. 顯示省略號 */
  /* 必須三者同時設定,且元素需有明確寬度 (table-layout: fixed + col 定寬) */
}

必要條件:表格需 table-layout: fixed,欄寬明確定義 (<col> 或 th/td width)。

場景二:允許自動換行 (多行顯示完整內容)

.cell-wrap {
  white-space: normal;       /* 允許換行 */
  word-break: break-word;    /* 現代標準:長單字在邊界斷行 */
  /* 兼容舊版:word-wrap: break-word; */
  /* 極端:word-break: break-all; (英文單字中間也斷) */
}

注意:儲存格高度會隨內容增長撐開。若需限制高度,可加 max-height + overflow: auto。

場景三:預設格式保留 (程式碼、日誌、詩歌)

.cell-pre {
  white-space: pre-wrap;     /* 保留空白、換行、自動換行 */
  font-family: monospace;    /* 等寬字體 */
  font-size: 0.85rem;
  line-height: 1.6;
}

完整響應式表格範例

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表格自動換行與溢出處理示範</title>
<style>
  .table-wrap { overflow-x: auto; margin: 1rem 0; border: 1px solid #eee; border-radius: 4px; }
  .data-table {
    border-collapse: collapse;
    width: 100%;
    min-width: 700px; /* 觸發容器滾動 */
    table-layout: fixed;
    font-size: 0.9rem;
  }
  .data-table col:nth-child(1) { width: 50px; }
  .data-table col:nth-child(2) { width: 200px; } /* 固定寬度測試溢出 */
  .data-table col:nth-child(3) { width: 30%; }
  .data-table col:nth-child(4) { width: 200px; }
  .data-table th, .data-table td {
    border: 1px solid #e0e0e0;
    padding: 10px 12px;
    vertical-align: top;
  }
  .data-table thead th { background: #f5f7fa; font-weight: 600; position: sticky; top: 0; }

  /* 欄位 1: 單行截斷省略號 */
  .data-table .col-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  /* 欄位 2: 允許換行 (中文自動斷行,長英文單字斷行) */
  .data-table .col-wrap {
    white-space: normal;
    word-break: break-word;
  }

  /* 欄位 3: 預設格式保留 (程式碼) */
  .data-table .col-pre {
    white-space: pre-wrap;
    font-family: 'Fira Code', 'Consolas', monospace;
    font-size: 0.8rem;
    background: #f8f8f8;
  }

  /* 欄位 4: 強制不換行 + 滾動 (罕見需求) */
  .data-table .col-scroll {
    display: block; /* 必須為 block 才能 overflow */
    max-height: 60px;
    overflow-y: auto;
    white-space: nowrap;
  }
</style>
</head>
<body>
<div class="table-wrap">
  <table class="data-table">
    <colgroup><col><col><col><col></colgroup>
    <thead>
      <tr>
        <th>ID</th>
        <th>單行截斷 (ellipsis)</th>
        <th>自動換行 (break-word)</th>
        <th>程式碼預設格式 (pre-wrap)</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td class="col-ellipsis">這是一段非常非常長的中文文字內容,超過欄寬會自動截斷顯示省略號...</td>
        <td class="col-wrap">ThisIsAVeryLongEnglishWordWithoutSpacesThatWillBreakAtBoundaryBecauseOfBreakWordPropertyAndChinese文字也會正常換行顯示。</td>
        <td class="col-pre">function hello() {
  console.log("Hello World");
  return true;
}</td>
      </tr>
      <tr>
        <td>2</td>
        <td class="col-ellipsis">短文字</td>
        <td class="col-wrap">正常文字換行無問題。</td>
        <td class="col-pre">const x = 1; const y = 2;</td>
      </tr>
    </tbody>
  </table>
</div>
</body>
</html>

table-layout: fixed 為何是前提?

  • auto (預設):瀏覽器**先讀取所有內容寬度**,再計算欄寬。**內容決定寬度**,CSS width 僅為建議,長內容會撐開。
  • fixed:瀏覽器**依據 <col>、<th> 寬度、或第一列內容**一次決定欄寬,**忽略後續內容寬度**。**寬度由開發者控制**,內容溢出由 overflow 處理。**渲染速度更快**。

舊版 IE / 郵件模板 相容方案

  • IE 不支援 word-break: break-word,需用 word-wrap: break-word (別名)。
  • 郵件模板:**不支援** table-layout: fixed, text-overflow: ellipsis, word-break。
    • 強制換行:在長字串中插入 <wbr> 或零寬空格 ​。
    • 截斷:只能後端截斷字串輸出,或用固定高度 overflow:hidden (Outlook 不支援)。

JavaScript 動態處理超長內容 (輔助方案)

// 為所有 td 自動添加 title 提示完整內容
document.querySelectorAll('td').forEach(td => {
  if (td.scrollWidth > td.clientWidth) {
    td.title = td.textContent.trim();
  }
});

// 或:點擊展開/摺疊長內容
function setupExpandableCells(selector) {
  document.querySelectorAll(selector).forEach(td => {
    const fullText = td.textContent.trim();
    if (td.scrollWidth <= td.clientWidth) return; // 未溢出
    td.dataset.full = fullText;
    td.classList.add('expandable');
    td.addEventListener('click', () => td.classList.toggle('expanded'));
  });
}

/* CSS */
td.expandable { cursor: pointer; position: relative; }
td.expandable::after { content: '...'; color: #0066cc; margin-left: 4px; }
td.expandable.expanded { white-space: normal; word-break: break-word; }
td.expandable.expanded::after { content: ' 收起'; }

結語

表格換行核心在於 **table-layout: fixed 確立寬度主導權** + **white-space/word-break/overflow-wrap/overflow 組合拳處理溢出**。根據內容性質選擇「截斷省略」、「自動換行」或「預設格式」,並輔以響應式容器滾動與 JS 互動增強,即能優雅解決所有表格內容顯示難題。

copyright © 萬盛學電腦網 all rights reserved