单行文本截断
div {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
浏览器原生支持,各大浏览器兼容性好;
缺点是不支持多行文本截断;
多行文本截断
-webkit-line-clamp 实现
div {
display: -webkit-box; /* 将对象作为弹性伸缩盒子模型显示 */
-webkit-box-orient: vertical; /* 设置或检索伸缩盒对象的子元素的排列方式 */
-webkit-line-clamp: 2; /* 2行,只有 webkit内核支持 */
word-break: break-all; /* 纯英文换行 */
overflow: hidden;
}
效果很好,但兼容性不好,只有webkit内核支持
定位 + 伪元素
原理:在后面追加一个伪元素,承载省略号的效果
缺点:省略号会始终一直显示
所以,如果确定文字内容一定会超出容器,这是一种比较好的方式。
div {
position: relative;
line-height: 20px;
height: 40px;
overflow: hidden;
word-break: break-all;
}
div::after {
content:"...";
font-weight:bold;
position:absolute;
bottom:0;
right:0;
padding:0 10px 0 30px;
line-height: 20px;
/* 为了展示效果更好 */
background-color: ;
background: -webkit-gradient(linear, left top, right top, from(transparent), to(white), color-stop(50%, white));
background: -moz-linear-gradient(to right, transparent, white 50%, white);
background: -o-linear-gradient(to right, transparent, white 50%, white);
background: -ms-linear-gradient(to right, transparent, white 50%, white);
background: linear-gradient(to right, transparent, white 50%, white);
}
浮动 + 伪元素
<style>
.wrap {
height: 40px;
line-height: 20px;
overflow: hidden;
}
.wrap .text {
float: right;
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: 2em;
/* 使盒子不占位置 */
margin-left: -2em;
/* 移动省略号位置 */
position: relative;
left: 100%;
top: -20px;
padding-right: 5px;
text-align: right;
background: -webkit-gradient(linear, left top, right top, from(transparent), to(white), color-stop(50%, white));
background: -moz-linear-gradient(to right, transparent, white 50%, white);
background: -o-linear-gradient(to right, transparent, white 50%, white);
background: -ms-linear-gradient(to right, transparent, white 50%, white);
background: linear-gradient(to right, transparent, white 50%, white);
}
</style>
<div class="wrap">
<div class="text">fadfadsfasd</div>
</div>
原文地址:https://github.com/happylindz/blog/issues/12
https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Images/Using_CSS_gradients
网友评论