实现一行或多行文本溢出省略效果 常用方法汇总

纯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'});

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值