文字超出容器顯示「...」是 UI 常見需求。單行極簡單,多行需特定技巧。本文涵蓋單行標準寫法、多行 WebKit 方案、跨瀏覽器漸進增強、JS 兜底方案。
.ellipsis-1 {
overflow: hidden; /* 隱藏溢出 */
white-space: nowrap; /* 強制不換行 */
text-overflow: ellipsis; /* 顯示省略號 */
/* 必須有固定寬度或 max-width */
width: 200px;
}
必要條件:區塊級元素(或 `inline-block`/`flex` 子項)+ 明確寬度 + 無 `wrap` 換行。
.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,允許換行 */
}
.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 判斷是否溢出,決定是否顯示漸層與「展開」按鈕 */
此法利用漸層淡出最後一行,視覺上暗示有更多內容,配合「展開」按鈕體驗更好。
// 簡易實現:二分法查找最大行數
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`)。
.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` 並做好兜底。