萬盛學電腦網

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

CSS 強制文字不換行與溢出省略:white-space、text-overflow、overflow 組合技

核心屬性組合

.nowrap-ellipsis {
  white-space: nowrap;   /* 強制不換行 */
  overflow: hidden;      /* 隱藏溢出 */
  text-overflow: ellipsis; /* 顯示省略號 … */
}

三者缺一不可:nowrap 防換行 → overflow:hidden 切斷視覺 → text-overflow 顯示標記。

white-space 完整取值

值空白處理換行處理適用場景
normal合併自動換行預設、一般文字
nowrap合併不換行單行截斷、導航項、表格儲存格
pre保留保留換行代碼區塊、詩歌
pre-wrap保留保留換行 + 自動換行用戶輸入內容顯示、日誌
pre-line合併保留換行 + 自動換行保留段落換行的文章
break-spaces保留(含換行機會)保留換行 + 自動換行精確保留空白序列

text-overflow 進階

text-overflow: clip;        /* 直接切斷,無標記 */
text-overflow: ellipsis;    /* 顯示 … (U+2026) */
text-overflow: "→ 更多";     /* 自定字串(現代瀏覽器支援) */

多行截斷(Line Clamp)

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  /* 注意:不需 white-space:nowrap */
}
  • 僅 WebKit/Blink 核心支援(Chrome, Edge, Safari, Opera)。
  • Firefox 需 JavaScript 方案或 -moz-box 方案(已棄用)。
  • 標準化進行中:line-clamp 屬性(CSS Overflow Module Level 3)。

表格儲存格強制不換行

td, th {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;  /* 必須有寬度限制 */
}
table { table-layout: fixed; width: 100%; }  /* 固定佈局算法,尊重 td 寬度 */

Flex/Grid 容器內的截斷陷阱

Flex 子元素/Grid 項目預設 min-width: auto(即內容最小寬度),導致 overflow:hidden 不生效。

.flex-item {
  min-width: 0;  /* 關鍵:允許壓縮至 0 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

RTL/垂直書寫模式下的邏輯屬性

.logical-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  /* 邏輯屬性自動適應 writing-mode */
}

無障礙考量

  • 省略號對螢幕閱讀器可能造成語意中斷。
  • 重要資訊(價格、標題、按鈕文字)不要截斷。
  • 提供 title 屬性或 aria-label 完整內容,或用 Tooltip 補充。

JavaScript 替代方案(跨瀏覽器多行截斷)

function clampText(el, lines) {
  const style = getComputedStyle(el);
  const lh = parseFloat(style.lineHeight);
  const maxH = lh * lines;
  if (el.scrollHeight > maxH) {
    let text = el.textContent;
    while (el.scrollHeight > maxH && text.length) {
      text = text.slice(0, -1);
      el.textContent = text + "…";
    }
  }
}

總結

單行截斷:white-space:nowrap + overflow:hidden + text-overflow:ellipsis。多行截斷:-webkit-line-clamp(現代瀏覽器)或 JS 兜底。Flex/Grid 子項必加 min-width:0。表格用 table-layout:fixed。重要內容勿截斷,輔以 Tooltip/aria-label 保障無障礙。

copyright © 萬盛學電腦網 all rights reserved