單行文本截斷
div {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
瀏覽器原生支持灸眼,各大瀏覽器兼容性好评腺;
缺點是不支持多行文本截斷杈女;
多行文本截斷
-webkit-line-clamp 實現(xiàn)
div {
display: -webkit-box; /* 將對象作為彈性伸縮盒子模型顯示 */
-webkit-box-orient: vertical; /* 設置或檢索伸縮盒對象的子元素的排列方式 */
-webkit-line-clamp: 2; /* 2行,只有 webkit內(nèi)核支持 */
word-break: break-all; /* 純英文換行 */
overflow: hidden;
}
效果很好豪诲,但兼容性不好顶捷,只有webkit內(nèi)核支持
定位 + 偽元素
原理:在后面追加一個偽元素,承載省略號的效果
缺點:省略號會始終一直顯示
所以屎篱,如果確定文字內(nèi)容一定會超出容器服赎,這是一種比較好的方式。
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