CSS to achieve text truncation Investigation code to achieve the following text exceeds the style code is automatically cut off:
.truncate-text-4 {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 4;
}
Using HTML fragments were tested as follows:
<style>
.my-div {
width: 300px;
margin: 10px auto;
background: #ddd;
}
</style>
<div class="my-div truncate-text-4">
How Not To Shuffle - The Knuth Fisher-Yates Algorithm. Written by Mike James.
Thursday, 16 February 2017. Sometimes simple algorithms are just wrong. In
this case shuffling an .... In other words as the array is scanned the element
under
</div>
running result: CSS by ellipsis truncating the text to achieve the effect of padding The problem Everything was perfect, until the container to add text padding after style.
.my-div {
width: 300px;
margin: 10px auto;
background: #ddd;
+ padding: 30px;
}
Now the effect is this: padding Destroyed the text truncation 因为 padding 占了元素内部空间,但这部分区域却是在元素内部的,所以不会受 overflow: hidden 影响。 解决办法 line-height 当设置的 line-height 适当时,或足够大时,可以将 padding 的部分抵消掉以实现将多余部分挤出可见范围的目标。
.my-div {
width: 300px;
margin: 10px auto;
background: #ddd;
padding: 30px;
+ line-height: 75px;
}
通过 line-height 修复 这种方式并不适用所有场景,因为不是所有地方都需要那么大的行高。 替换掉 padding padding 无非是要给元素的内容与边框间添加间隔,或是与别的元素间添加间隔。这里可以考虑其实方式来替换。 比如 margin 。但如果元素有背景,比如本例中,那 margin 的试就不适用了,因为元素 margin 部分是不带背景的。 还可用 border 代替。
.my-div {
width: 300px;
margin: 10px auto;
background: #ddd;
- padding: 30px;
+ border: 30px solid transparent;
}
使用 border 替换 padding 毫不意外,它仍然有它的局限性。就是在元素本身有自己的 border 样式要求的时候,就会冲突了。 将边距与内容容器分开 比较普适的方法可能就是它了,即将内容与边距分开到两个元素上,一个元素专门用来实现边距,一个元素用来实现文本的截断。这个好理解,直接看代码:
<div className="my-div">
<div className="truncate-text-4">
How Not To Shuffle - The Knuth Fisher-Yates Algorithm. Written by Mike
James. Thursday, 16 February 2017. Sometimes simple algorithms are just
wrong. In this case shuffling an .... In other words as the array is scanned
the element under
</div>
</div>
而我们的样式可以保持不动。 将边距与内容容器分开 相关资源
|