萬盛學電腦網

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

CSS 文字溢出省略號完整實作:單行、多行、表格儲存格通用方案

核心三件套:單行省略號

.ellipsis-1 {
  overflow: hidden;          /* 隱藏超出內容 */
  white-space: nowrap;       /* 強制不換行 */
  text-overflow: ellipsis;   /* 顯示 … */
  /* 必須指定寬度或 max-width */
}

適用於導航列、麵包屑、卡片標題等單行截斷場景。

多行省略號:-webkit-line-clamp 方案

.ellipsis-3 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;     /* 顯示 3 行 */
  overflow: hidden;
  /* 不需 white-space: nowrap */
}
  • 支援:Chrome、Edge、Firefox 68+、Safari、Opera、移動端 WebKit 內核。
  • 缺點:非標準屬性、無法自訂省略符號、無法在中間插入「展開」按鈕。

表格儲存格省略號:關鍵在 table-layout: fixed

table {
  table-layout: fixed;       /* 固定欄寬,啟用儲存格截斷 */
  width: 100%;
}
td, th {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 0.5rem;
}

若無 table-layout: fixed,儲存格會被內容撐開,省略號失效。

完整範例:響應式表格含省略號

<style>
.responsive-table {
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
}
.responsive-table th,
.responsive-table td {
  border: 1px solid #ddd;
  padding: 8px 12px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.responsive-table th { background: #f5f5f5; font-weight: 600; }
</style>

<table class="responsive-table">
  <thead>
    <tr>
      <th style="width: 30%">商品名稱</th>
      <th style="width: 40%">詳細描述</th>
      <th style="width: 15%">分類</th>
      <th style="width: 15%">狀態</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>超長商品名稱超長商品名稱超長商品名稱超長商品名稱</td>
      <td>這是一段非常非常長的描述文字這是一段非常非常長的描述文字這是一段非常非常長的描述文字</td>
      <td>電子產品</td>
      <td>上架中</td>
    </tr>
  </tbody>
</table>

進階:自訂省略符號與「展開」交互

純 CSS 無法自訂省略符號(永遠是 `…`),需 JavaScript 輔助:

/* CSS 部分 */
.expandable {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  position: relative;
}
.expandable::after {
  content: '';
  position: absolute;
  bottom: 0; right: 0;
  width: 60px; height: 1.5em;
  background: linear-gradient(to right, transparent, white);
  pointer-events: none;
}
.expandable.expanded {
  -webkit-line-clamp: unset;
  max-height: none;
}
.expandable.expanded::after { display: none; }
/* JS 部分 */
document.querySelectorAll('.expandable').forEach(el => {
  const btn = document.createElement('button');
  btn.textContent = '展開';
  btn.className = 'expand-btn';
  el.parentNode.insertBefore(btn, el.nextSibling);
  btn.addEventListener('click', () => el.classList.toggle('expanded'));
});

避坑檢查清單

  • ✅ 容器有明確 width/max-width 或父層限制寬度。
  • ✅ overflow: hidden 設在同一個元素上。
  • ✅ 多行方案需 display: -webkit-box + -webkit-box-orient: vertical。
  • ✅ 表格必須 table-layout: fixed。
  • ❌ 不要在 <td> 加 display: block,會破壞表格佈局。

總結

單行用 white-space: nowrap 三件套;多行用 -webkit-line-clamp;表格加 table-layout: fixed。這三套組合覆蓋 95% 實務需求。若需自訂省略符號或展開互動,請引入極輕量 JavaScript 輔助,保持 CSS 純粹與高效能。

copyright © 萬盛學電腦網 all rights reserved