纯CSS方案
单行比较简单:
/* css部分 */
.ellipsis{
overflow: hidden;
text-overflow:ellipsis;
white-space: nowrap;
}
<!-- html部分 -->
<div class="ellipsis" style="width:100px">hello world - hello world - hello world</div>
实现效果
多行的:
/* css部分 */
.ellipsis-multi{
overflow:hidden;
/* 老浏览器写法 只兼容webkit内核浏览器 */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
}
/* 防止英文不换行 */
.break{
word-wrap:break-word;
word-break:break-all;
}
<!-- html部分 -->
<div class="ellipsis-multi break" style="width:100px">hello world - hello world - hello world - hello world - hello world - hello world - hello world - hello world - hello world</div>
实现效果
这个方法IE不兼容(Edge是可以的),Firefox我使用的是新版本,貌似已经支持了-webikt-前缀,经过我的测试时可以通过的。
还有一种考虑IE的妥协型写法,且必须是文字一定溢出的情况下:
.ellipsis-ie{
position: relative;
line-height: 20px;
max-height: 40px;
overflow: hidden;
}
.ellipsis-ie:after{
content: "...";
position: absolute;
bottom: 0;
right: 0;
padding-left: 40px;
/* IE10+ */
background: linear-gradient(to right, transparent, #fff 55%);
/* 针对IE9 */
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#1471da, endColorstr=#1C85FB);
}
思路就是用一个渐变透明的图层这改一下,算是一种折中方案,但效果不是很好
css只能做到这个地步,如果要完美实现还得靠js,这里就不上手写js了,github上有个clamp.js专门解决这类问题https://github.com/josephschmitt/Clamp.js
// 官方示例如下
//Single line
$clamp(myHeader, {clamp: 1});
//Multi-line
$clamp(myHeader, {clamp: 3});
//Auto-clamp based on available height
$clamp(myParagraph, {clamp: 'auto'});
//Auto-clamp based on a fixed element height
$clamp(myParagraph, {clamp: '35px'});