如何使用CSS实现文本最多显示两行并截断超出内容
如何使用CSS实现文本最多显示两行并截断超出内容
嗨,我完全懂你的需求啦!你现在用的是单行文本截断的代码,所以只会把所有内容挤在一行里截断,而你想要的是让文本先自动换行到第二行,再把超出第二行的部分用省略号截断,对吧?
其实只要调整几个CSS属性就能实现,把你原来的p标签样式改成下面这样就行:
body{ font-family:sans-serif; } p{ background-color:yellow; font-size:1.5rem; width:300px; /** 修改后的多行截断核心属性 **/ display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; }
我给你解释下每个核心属性的作用:
display: -webkit-box:把段落元素转换成WebKit内核专用的弹性盒子布局,为多行截断提供基础-webkit-line-clamp: 2:直接指定文本最多显示2行,超过的部分就会被截断-webkit-box-orient: vertical:设置盒子内部的元素排列方向为垂直,这样文本才能按行从上到下排列overflow: hidden:把超出指定行数的内容隐藏起来text-overflow: ellipsis:在被截断的末尾显示省略号,提示用户还有更多内容
你的HTML部分不用改,还是原来的结构:
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
这样设置之后,文本就会先自动换行到第二行,超出第二行的部分就会被截断成你想要的效果:
Lorem Ipsum is simply dummy
text of the printing and...
备注:内容来源于stack exchange,提问作者Happy1234




