萬盛學電腦網

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

CSS `text-overflow:ellipsis` 實現單行/多行文字溢出省略號完整指南

文字超出容器顯示「...」是 UI 常見需求。單行極簡單,多行需特定技巧。本文涵蓋單行標準寫法、多行 WebKit 方案、跨瀏覽器漸進增強、JS 兜底方案。

單行省略號:標準三件套(全瀏覽器支援)

.ellipsis-1 {
  overflow: hidden;        /* 隱藏溢出 */
  white-space: nowrap;     /* 強制不換行 */
  text-overflow: ellipsis; /* 顯示省略號 */
  /* 必須有固定寬度或 max-width */
  width: 200px; 
}

必要條件:區塊級元素(或 `inline-block`/`flex` 子項)+ 明確寬度 + 無 `wrap` 換行。

多行省略號:`-webkit-line-clamp`(現代主流方案)

.ellipsis-3 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;      /* 顯示行數 */
  overflow: hidden;
  /* 不需要 white-space:nowrap */
  width: 300px;
  line-height: 1.5;
  height: 4.5em; /* 3 * 1.5em,可選:防止佈局抖動 */
}

支援:Chrome、Edge、Firefox 68+、Safari、Opera、iOS Safari、Android WebView。**不支援 IE**。

跨瀏覽器漸進增強策略

.ellipsis-multi {
  /* 1. 基礎:單行兜底 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 300px;

  /* 2. 現代瀏覽器:多行 */
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  white-space: normal; /* 覆蓋 nowrap,允許換行 */
}
  • 不支援 `-webkit-line-clamp` 的瀏覽器(IE)自動退化為單行省略。
  • 支援的瀏覽器顯示 3 行省略。

純 CSS 多行方案(無 WebKit 依賴,IE10+)

.ellipsis-fade {
  position: relative;
  height: 4.5em;          /* 3行 * 1.5em */
  line-height: 1.5em;
  overflow: hidden;
}
.ellipsis-fade::after {
  content: '';
  position: absolute;
  right: 0; bottom: 0;
  width: 60px; height: 1.5em;
  background: linear-gradient(to right, transparent, white 80%);
  pointer-events: none;
}
/* 配合 JS 判斷是否溢出,決定是否顯示漸層與「展開」按鈕 */

此法利用漸層淡出最後一行,視覺上暗示有更多內容,配合「展開」按鈕體驗更好。

JS 兜底方案:Clamp.js / 自實現

// 簡易實現:二分法查找最大行數
function clampText(el, maxLines) {
  const style = getComputedStyle(el);
  const lineHeight = parseFloat(style.lineHeight);
  const maxHeight = lineHeight * maxLines;
  
  if (el.scrollHeight <= maxHeight) return; // 無需截斷
  
  let text = el.textContent;
  let lo = 0, hi = text.length;
  while (lo < hi) {
    const mid = (lo + hi + 1) >> 1;
    el.textContent = text.slice(0, mid) + '…';
    if (el.scrollHeight <= maxHeight) lo = mid;
    else hi = mid - 1;
  }
  el.textContent = text.slice(0, lo) + '…';
}

// 使用
document.querySelectorAll('.js-clamp-3').forEach(el => clampText(el, 3));

生產環境建議用成熟庫:Clamp.js、ftscroller 或框架專用組件(Vue: `v-clamp`、React: `react-lines-ellipsis`)。

Flex/Grid 容器中的陷阱

  • Flex 子項需加 `min-width: 0` 或 `overflow: hidden` 才能讓 `text-overflow` 生效。
  • Grid 同理:`min-width: 0` 或 `overflow: hidden`。
.card {
  display: flex;
}
.card .title {
  min-width: 0;      /* 關鍵! */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

總結選型表

需求推薦方案支援度
單行`overflow:hidden; white-space:nowrap; text-overflow:ellipsis`全瀏覽器(IE6+)
多行(現代專案)`-webkit-line-clamp` + 漸進增強主流現代瀏覽器(含移動端)
多行(需支援 IE)JS Clamp.js / 漸層淡出 + 展開按鈕全瀏覽器
多行 + 動態展開/收合JS 方案(可控性最強)全瀏覽器

根據專案瀏覽器支援矩陣與互動需求選擇方案,單行永遠用標準三件套,多行優先 `-webkit-line-clamp` 並做好兜底。

copyright © 萬盛學電腦網 all rights reserved