Skip to content

文本省略号

单行

css
{
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

多行(webkit内核)

css
{
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

兼容

html
<div class="multiLineOverflow">
  multiline
</div>
<div class="multiLineOverflow">
  <span>multiline texts, multiline texts, multiline texts, multiline texts</span>
</div>
css
body {
  --height: 1.2rem;
  --lines: 3;
  --linesHeight: calc(var(--height) * var(--lines));
}

.multiLineOverflow {
  position: relative;
  width: 80px;
  line-height: var(--height);
  height: var(--linesHeight);
  overflow: hidden;
}

.multiLineEllipsis::before {
  content: "...";
  position: absolute;
  right: 0;
  top: calc(var(--linesHeight) - var(--height));
}

用 js 判断是否超出行数,getClientRects,可以用于行内元素,获取每一行的位置信息

js
const doms = document.querySelectorAll("span");
for (const dom of doms) {
  if (dom.getClientRects().length > 3) {
    dom.parentElement.classList.add("multiLineEllipsis");
  }
}