CSS文本超过两行用省略号代替(兼容所有浏览器)
通过float特性实现多行文字截断效果,基本原理:
有个三个盒子 div,粉色盒子左浮动,浅蓝色盒子和黄色盒子右浮动:
1、当浅蓝色盒子的高度低于粉色盒子,黄色盒子仍会处于浅蓝色盒子右下方。
2、如果浅蓝色盒子文本过多,高度超过了粉色盒子,则黄色盒子不会停留在右下方,而是掉到了粉色盒子下。
好了,这样两种状态的两种展示形式已经区分开了,那么我们可以将黄色盒子进行相对定位,将内容溢出的黄色盒子移动到文本内容右下角,而未溢出的则会被移到外太空去了,只要我们使用 overflow:hidden就可以隐藏掉。
基本原理就是这样,我们可以将浅蓝色区域想象成标题,黄色区域想象为省略号效果。那么你可能会觉得粉色盒子占了空间,那岂不是标题会整体延后了吗,这里可以通过 margin 的负值来出来,设置浅蓝色盒子的 margin-left 的负值与粉色盒子的宽度相同,标题也能正常显示。
具体代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.wrap {
height: 40px;
line-height: 20px;
overflow: hidden;
}
.wrap .text {
float: left;
margin-left: -5px;
width: 100%;
word-break: break-all;
}
.wrap::before {
float: left;
width: 5px;
content: '';
height: 40px;
}
.wrap::after {
float: right;
content: "...";
height: 20px;
line-height: 20px;
/* 为三个省略号的宽度 */
width: 3em;
/* 使盒子不占位置 */
margin-left: -3em;
/* 移动省略号位置 */
position: relative;
left: 100%;
top: -20px;
padding-right: 5px;
background-color: #FFF;
}
</style>
</head>
<body>
<div class="wrap">
<div class="text">
That's the basic idea. You can imagine the light blue region as the title, and the yellow region as the ellipsis. Then you may think that the pink box takes up space, but will the title be delayed as a whole? Here you can come out by the negative value of margin. Set the negative value of the pale blue box to be the same width as the pink box, and the title can also be displayed normally.
</div>
</div>
</body>
</html>
这里我目前看到最巧妙的方式了。只需要支持 CSS 2.1 的特性就可以了,它的优点有:
兼容性好,对各大主流浏览器有好的支持。
响应式截断,根据不同宽度做出调整。
文本超出范围才显示省略号,否则不显示省略号。
至于缺点,因为我们是模拟省略号,所以显示位置有时候没办法刚刚好,所以可以考虑:
加一个渐变效果,贴合文字,就像上述 demo 效果一样。
添加 word-break:break-all; 使一个单词能够在换行时进行拆分,这样文字和省略号贴合效果更佳。
这个方法应该是我看到最好的用纯 CSS 处理的方式了,如果你有更好的方法,欢迎留言交流!