CSS实现单行溢出显示省略号很是简单:
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
Firefox(从68版开始)支持-webkit-line-clamp实现多行文本显示省略号,-webkit-line-clamp浏览器兼容性方面支持的还不错。
不过还有另一种CSS方法实现多行文本显示省略号,所以称之为真正的CSS技巧。
1、设置line-height行高
假设一个元素的行高为1.4rem,最多只显示三行文本。则把它的最大高度设为1.4rem*3,这里设置了一个全局变量line-height。
html {
--lh: 1.4rem;
line-height: var(--lh);
}
2、设置max-height最大高度
.truncate-overflow {
--max-lines: 3;
max-height: calc(var(--lh) * var(--max-lines));
overflow: hidden;
}
3、显示省略号
.truncate-overflow::before {
content: "...";
position: absolute;
bottom: 0;
right: 0;
}
4、当文字内容太短时,把省略号盖住。
用另一个伪元素制作一个与后面背景相同的小盒子,并将它放在省略号的顶部以覆盖它。
.truncate-overflow::after {
content: "";
position: absolute;
right: 0; /* note: not using bottom */
width: 1rem;
height: 1rem;
background: white;
}
注意:这里不要设置bottom(inset-block-end)属性。不然框就会放在内容底部而不是相对父级的底部,这一点很重要。
不信,你可以给框设为红色背景,就可以看到像下面这样:
全部代码如下:
<p>
多行文本显示省略号
</p>
<p class="truncate-overflow">
检测JavaScript基本功掌握的怎么样以及平时有没有去深入研究一些方法的实现,简而言之,就是有没有折腾精神。在模拟之前我们先要明白和了解原生call和apply、bind方法是什么
</p>
<p class="truncate-overflow">
JS压缩后IE低版本不兼容,试试把ugli
</p>
<p class="truncate-overflow">
IE不标准的地方,unshift方法会返回新数组的长度,但IE6与IE7则返回undefined。
</p>
:root {
/* Not my favorite that line-height has to be united, but needed */
--lh: 1.4rem;
}
html {
max-width: 22rem;
margin: 2rem auto;
line-height: var(--lh);
}
.truncate-overflow {
--max-lines: 3;
position: relative;
max-height: calc(var(--lh) * var(--max-lines));
overflow: hidden;
padding-right: 1rem; /* space for ellipsis */
}
.truncate-overflow::before {
position: absolute;
content: "...";
/* tempting... but shows when lines == content */
/* top: calc(var(--lh) * (var(--max-lines) - 1)); */
/*
inset-block-end: 0;
inset-inline-end: 0;
*/
bottom: 0;
right: 0;
}
.truncate-overflow::after {
content: "";
position: absolute;
inset-inline-end: 0;
right: 0;
margin-bottom:-5px;
/* missing bottom on purpose*/
width: 1rem;
height: 1.2rem;
background: #fff;
}