.ellipsis {
overflow: hidden; /* 必須隱藏溢出 */
white-space: nowrap; /* 單行:強制不換行 */
text-overflow: ellipsis; /* 顯示省略號 (U+2026) */
}
關鍵三要素:overflow: hidden + white-space: nowrap + text-overflow: ellipsis。
.single-line-truncate {
width: 200px; /* 必須有寬度限制 */
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
/* 可選:防止中文斷字 */
word-break: keep-all;
}
.multi-line-truncate {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3; /* 顯示行數 */
overflow: hidden;
/* 兼容性補充 */
text-overflow: ellipsis; /* 部分瀏覽器需要 */
}
支援:Chrome、Safari、Edge、Firefox 68+、Opera。無標準化 W3C 規範,但已成事實標準。
.standard-multi-line {
overflow: hidden;
text-overflow: ellipsis;
/* 草案階段,尚未廣泛支援 */
/* block-ellipsis: auto; */
}
.css-only-multi-line {
/* 利用 line-height 與 max-height 計算行數 */
line-height: 1.5;
max-height: 4.5em; /* 3 行 = 1.5 * 3 */
overflow: hidden;
position: relative;
}
.css-only-multi-line::after {
content: '...';
position: absolute;
right: 0;
bottom: 0;
background: linear-gradient(to right, transparent, white 50%);
padding-left: 0.5em;
/* 僅視覺上模擬省略號,不影響選取/複製 */
}
| 維度 | CSS text-overflow | JS substring |
|---|---|---|
| 效能 | 瀏覽器原生渲染,極快 | 需計算、操作 DOM,較慢 |
| 響應式 | 自動適應容器寬度變化 | 需監聽 resize 重新計算 |
| 無障礙 | 完整文字保留在 DOM,螢幕閱讀器可讀 | 文字被截斷,螢幕閱讀器讀到截斷版 |
| 選取/複製 | 用戶可選取完整文字 | 只能選取截斷後文字 |
| 多語言 | 自動處理中日韓無空格換行 | 需複雜邏輯判斷字符寬度 |
| 維護 | 純樣式,職責分離 | 業務邏輯耦合顯示邏輯 |
.custom-ellipsis::after {
content: '【更多】';
color: #3498db;
font-size: 0.85em;
}
/* 配合單行截斷 */
.single-line-custom {
overflow: hidden;
white-space: nowrap;
text-overflow: ''; /* 隱藏原生省略號 */
padding-right: 3em; /* 為自定義省略號留空間 */
}
.single-line-custom::after {
content: '【更多】';
position: absolute;
right: 0;
top: 0;
}
.cjk-text {
word-break: keep-all; /* CJK 文字不斷字,整詞換行 */
overflow-wrap: break-word; /* 非 CJK 長單詞允許斷行 */
}
text-overflow: ellipsis:全瀏覽器(IE6+)-webkit-line-clamp:Chrome 17+、Safari 6.1+、Firefox 68+、Edge 79+line-clamp(標準化):Chrome 111+、Edge 111+、Firefox 119+、Safari 16.4+CSS3 text-overflow: ellipsis 配合 overflow: hidden 是單行截斷的黃金標準;多行截斷採用 -webkit-line-clamp 事實標準,新標準 line-clamp 正逐步普及。**完全替代 JavaScript substring**,在效能、響應式、無障礙、維護性全方位優勢。建立專案通用工具類 .truncate-1、.truncate-2、.truncate-3 即可覆蓋 95% 場景。