.nowrap-ellipsis {
white-space: nowrap; /* 強制不換行 */
overflow: hidden; /* 隱藏溢出 */
text-overflow: ellipsis; /* 顯示省略號 … */
}
三者缺一不可:nowrap 防換行 → overflow:hidden 切斷視覺 → text-overflow 顯示標記。
| 值 | 空白處理 | 換行處理 | 適用場景 |
|---|---|---|---|
normal | 合併 | 自動換行 | 預設、一般文字 |
nowrap | 合併 | 不換行 | 單行截斷、導航項、表格儲存格 |
pre | 保留 | 保留換行 | 代碼區塊、詩歌 |
pre-wrap | 保留 | 保留換行 + 自動換行 | 用戶輸入內容顯示、日誌 |
pre-line | 合併 | 保留換行 + 自動換行 | 保留段落換行的文章 |
break-spaces | 保留(含換行機會) | 保留換行 + 自動換行 | 精確保留空白序列 |
text-overflow: clip; /* 直接切斷,無標記 */
text-overflow: ellipsis; /* 顯示 … (U+2026) */
text-overflow: "→ 更多"; /* 自定字串(現代瀏覽器支援) */
.line-clamp-3 {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
/* 注意:不需 white-space:nowrap */
}
-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 項目預設 min-width: auto(即內容最小寬度),導致 overflow:hidden 不生效。
.flex-item {
min-width: 0; /* 關鍵:允許壓縮至 0 */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.logical-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
/* 邏輯屬性自動適應 writing-mode */
}
title 屬性或 aria-label 完整內容,或用 Tooltip 補充。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 保障無障礙。