.ellipsis {
white-space: nowrap; /* 1. 強制不換行 */
overflow: hidden; /* 2. 隱藏溢出內容 */
text-overflow: ellipsis; /* 3. 溢出處顯示省略號 (…) */
}
<style>
.news-list {
width: 300px;
border: 1px solid #ddd;
border-radius: 8px;
overflow: hidden;
font-family: 'Microsoft JhengHei', sans-serif;
}
.news-item {
padding: 12px 16px;
border-bottom: 1px solid #eee;
transition: background 0.2s;
}
.news-item:last-child { border-bottom: none; }
.news-item:hover { background: #f9f9f9; }
.news-title {
display: block;
font-size: 14px;
font-weight: 500;
color: #1a1a1a;
/* 核心:單行省略號 */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.news-meta {
margin-top: 4px;
font-size: 12px;
color: #999;
}
</style>
<div class="news-list">
<a href="#" class="news-item">
<span class="news-title">這是一個非常非常非常長的新聞標題會被截斷顯示省略號</span>
<span class="news-meta">2024-01-15 10:30</span>
</a>
<a href="#" class="news-item">
<span class="news-title">短標題</span>
<span class="news-meta">2024-01-15 09:15</span>
</a>
</div>
.multi-line-ellipsis {
display: -webkit-box;
-webkit-line-clamp: 3; /* 顯示行數 */
-webkit-box-orient: vertical;
overflow: hidden;
/* 注意:不需要 white-space: nowrap */
text-overflow: ellipsis; /* 可選:部分瀏覽器需要 */
line-height: 1.5; /* 必須設置行高 */
max-height: 4.5em; /* line-height × 行數,防止高度異常 */
}
支援:Chrome、Safari、Edge (Chromium)、Firefox 68+(需啟用佈局引擎標誌)。
降級:不支援瀏覽器顯示完整文本(無省略號)。
.standard-line-clamp {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
/* 未來標準語法(草案階段) */
/* line-clamp: 3; */
}
// 純 JS 方案:按像素高度截斷
function clampText(element, maxLines) {
const lineHeight = parseFloat(getComputedStyle(element).lineHeight);
const maxHeight = lineHeight * maxLines;
if (element.scrollHeight <= maxHeight) return;
let text = element.textContent;
let low = 0, high = text.length;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
element.textContent = text.slice(0, mid) + '…';
if (element.scrollHeight > maxHeight) {
high = mid - 1;
} else {
low = mid + 1;
}
}
element.textContent = text.slice(0, high) + '…';
}
// 使用
document.querySelectorAll('.clamp-3').forEach(el => clampText(el, 3));
.flex-container {
display: flex;
gap: 16px;
}
.flex-item {
flex: 1;
min-width: 0; /* 關鍵!允許 flex 子項收縮至 0,否則 text-overflow 失效 */
}
.flex-item .title {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.table td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px; /* 必須給定寬度或 max-width */
}
/* 表格佈局固定 */
.table {
table-layout: fixed; /* 關鍵:固定佈局算法,允許 td 寬度生效 */
width: 100%;
}
[dir="rtl"] .ellipsis {
direction: rtl; /* 確保省略號在左側 */
text-align: right;
}
/* 邏輯屬性(現代) */
.ellipsis {
overflow-inline: hidden;
text-overflow: ellipsis;
}
white-space: nowrapoverflow: hidden(或非 visible)min-width: 0table-layout: fixeddisplay: inline(需改為 inline-block/block/flex)float 干擾min-width: 0,Table 需 table-layout: fixed