萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 文字溢出省略號:單行與多行實現

單行省略 (經典三要素)

.ellipsis-1 {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
  • white-space: nowrap 強制不換行。
  • overflow: hidden 切掉溢出部分。
  • text-overflow: ellipsis 顯示「…」標記。

表格儲存格套用技巧

table { table-layout: fixed; width: 100%; }
th, td {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

table-layout: fixed 讓欄寬由 `` 或第一行決定,不再被內容撐開,省略號才生效。

多行省略 (WebKit Line Clamp)

.ellipsis-3 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;   /* 顯示 3 行 */
  overflow: hidden;
}

支援:Chrome、Edge、Firefox 68+、Safari、Opera。不支援 IE。

多行省略:純 CSS 方案 (無 -webkit-)

.ellipsis-clamp {
  line-height: 1.5;
  max-height: 4.5em;        /* 3 行 = 1.5 * 3 */
  overflow: hidden;
  position: relative;
}
.ellipsis-clamp::after {
  content: '...';
  position: absolute;
  right: 0; bottom: 0;
  padding-left: 0.5em;
  background: linear-gradient(to right, transparent, white 50%);
}

利用漸層遮罩實現「漸隱+省略號」,相容性極佳,但需固定行高且背景為純色。

JS 兜底方案 (Clamp.js / textClamp)

需精確控制行數、支援 HTML 標籤、或舊瀏覽器時,仍建議使用成熟 JS 庫。

copyright © 萬盛學電腦網 all rights reserved