如题,纯 CSS 多行文本溢出省略号。单行文本溢出省略号一般我们都知道实现方法。
.xxx {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
那么如果多行文本应该怎么做呢?Chrome 走在时代前沿,可以使用 -webkit-line-clamp 属性来实现,这个属性已经有些年头,但是其他浏览器仍然不支持,一声叹息。
.xxx {
display:-webkit-box;
-webkit-line-clamp:2;
-webkit-box-orient:vertical;
overflow:hidden;
}
-webkit-line-clamp 为行数,如果显示3行,则设置为3即可。
悲剧的是 -webkit-line-clamp 只有 webkit 内核支持,于是我们要想办法解决这个问题,纯 css 完美实现是不显示了,只能优雅降级,可以使用下面的方案,把最大高度设置为n倍行高,然后溢出部分隐藏即可。
.xxx {
line-height: 1.2;
max-height: 2.4em;
overflow: hidden;
}
这样做的好处是可以忽略文本的长度,即使文本很短不会出现问题。如果确定文本是肯定溢出的,还可以使用 ::after 伪类来模拟…
大致代码
.xxx {
line-height: 1.2;
max-height: 2.4em;
overflow: hidden;
position: relative;
}
.xxx:after {
content:"...";
position:absolute;
bottom: 0;
right: 0;
background-color: #fff;
}
考虑到文本不一定会溢出,最终解决方案推荐
.xxx {
line-height: 1.2;
max-height: 2.4em;
display:-webkit-box;
-webkit-line-clamp:2;
-webkit-box-orient:vertical;
overflow:hidden;
}
全文完。
作者:大发
本文首发于:纯 CSS 多行文本溢出省略号-垃圾站
Comments:0