(编辑:jimmy 日期: 2024/11/1 浏览:2)
在我们的日常开发工作中,文本溢出截断省略是很常见的一种需考虑的业务场景细节。看上去 “稀松平常” ,但在实现上却有不同的区分,是单行截断还是多行截断?多行的截断判断是基于行数还是基于高度?这些问题之下,都有哪些实现方案?他们之间的差异性和场景适应性又是如何?
一般来说,在做这样文字截断效果时我们更多是希望:
基于上述的准则,下面我们通过编码实践,给出一些答案。
单行文本溢出省略
核心 CSS 语句
优点
短板
适用场景
Demo
<div class="demo"> 床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光 </div>
.demo { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
效果示例
多行文本溢出省略(-webkit-line-clamp)
核心 CSS 语句
优点
短板
兼容性一般: -webkit-line-clamp 属性只有 WebKit 内核的浏览器才支持
适用场景
多适用于移动端页面,因为移动设备浏览器更多是基于 WebKit 内核
Demo
<div class="demo"> 床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光 </div>
.demo { display: -webkit-box; overflow: hidden; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
效果示例
多行文本溢出省略(伪元素 + 定位)
核心 CSS 语句
优点
短板
适用场景
文字内容较多,确定文字内容一定会超过容器的
Demo
<div class="demo"> 床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光 </div>
.demo { position: relative; line-height: 18px; height: 36px; overflow: hidden; word-break: break-all; } .demo::after { content:"..."; font-weight:bold; position:absolute; bottom:0; right:0; padding:0 20px 1px 45px; /* 为了展示效果更好 */ background: -webkit-gradient(linear, left top, right top, from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white)); background: -moz-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white); background: -o-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white); background: -ms-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white); background: linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white); }
效果示例
多行文本溢出省略(Float)
核心 CSS 语句
优点
短板
省略号显示可能不会刚刚好,有时会遮住一半文字,跟文字没有贴合的很紧密
适用场景
文字内容较多,确定文字内容一定会超过容器的
Demo
<div class="demo"> <div class="text"> 床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光床前明月光 </div> </div>
.demo { height: 40px; line-height: 20px; overflow: hidden; } .demo .text { float: right; margin-left: -5px; width: 100%; word-break: break-all; } .demo::before { float: left; width: 5px; content: ""; height: 40px; } .demo::after { float: right; content: "..."; height: 20px; line-height: 20px; padding-right: 5px; text-align: right; width: 3em; margin-left: -3em; position: relative; left: 100%; top: -20px; padding-right: 5px; /* 为了展示效果更好 */ background: -webkit-gradient( linear, left top, right top, from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white) ); background: -moz-linear-gradient( to right, rgba(255, 255, 255, 0), white 50%, white ); background: -o-linear-gradient( to right, rgba(255, 255, 255, 0), white 50%, white ); background: -ms-linear-gradient( to right, rgba(255, 255, 255, 0), white 50%, white ); background: linear-gradient( to right, rgba(255, 255, 255, 0), white 50%, white ); }
效果示例