.ellipsis-1 {
overflow: hidden; /* 隱藏超出內容 */
white-space: nowrap; /* 強制不換行 */
text-overflow: ellipsis; /* 顯示 … */
/* 必須指定寬度或 max-width */
}
適用於導航列、麵包屑、卡片標題等單行截斷場景。
-webkit-line-clamp 方案.ellipsis-3 {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3; /* 顯示 3 行 */
overflow: hidden;
/* 不需 white-space: nowrap */
}
table-layout: fixedtable {
table-layout: fixed; /* 固定欄寬,啟用儲存格截斷 */
width: 100%;
}
td, th {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
padding: 0.5rem;
}
若無 table-layout: fixed,儲存格會被內容撐開,省略號失效。
<style>
.responsive-table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
}
.responsive-table th,
.responsive-table td {
border: 1px solid #ddd;
padding: 8px 12px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.responsive-table th { background: #f5f5f5; font-weight: 600; }
</style>
<table class="responsive-table">
<thead>
<tr>
<th style="width: 30%">商品名稱</th>
<th style="width: 40%">詳細描述</th>
<th style="width: 15%">分類</th>
<th style="width: 15%">狀態</th>
</tr>
</thead>
<tbody>
<tr>
<td>超長商品名稱超長商品名稱超長商品名稱超長商品名稱</td>
<td>這是一段非常非常長的描述文字這是一段非常非常長的描述文字這是一段非常非常長的描述文字</td>
<td>電子產品</td>
<td>上架中</td>
</tr>
</tbody>
</table>
純 CSS 無法自訂省略符號(永遠是 `…`),需 JavaScript 輔助:
/* CSS 部分 */
.expandable {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
position: relative;
}
.expandable::after {
content: '';
position: absolute;
bottom: 0; right: 0;
width: 60px; height: 1.5em;
background: linear-gradient(to right, transparent, white);
pointer-events: none;
}
.expandable.expanded {
-webkit-line-clamp: unset;
max-height: none;
}
.expandable.expanded::after { display: none; }
/* JS 部分 */
document.querySelectorAll('.expandable').forEach(el => {
const btn = document.createElement('button');
btn.textContent = '展開';
btn.className = 'expand-btn';
el.parentNode.insertBefore(btn, el.nextSibling);
btn.addEventListener('click', () => el.classList.toggle('expanded'));
});
width/max-width 或父層限制寬度。overflow: hidden 設在同一個元素上。display: -webkit-box + -webkit-box-orient: vertical。table-layout: fixed。<td> 加 display: block,會破壞表格佈局。單行用 white-space: nowrap 三件套;多行用 -webkit-line-clamp;表格加 table-layout: fixed。這三套組合覆蓋 95% 實務需求。若需自訂省略符號或展開互動,請引入極輕量 JavaScript 輔助,保持 CSS 純粹與高效能。