如何实现段落文本两行后溢出显示省略号?
问题背景
我参考过Stack Overflow上的《Unable to get ellipsis for Multiline Paragraph》问题,想要实现文本在两行后显示省略号并截断的效果,但目前设置后,文本在显示省略号后仍会继续展示剩余内容。我尝试过将段落放入固定宽高的div中、为段落应用核心省略号CSS属性、使用text-overflow,但均未解决问题。
预期效果
文本在两行后截断并显示省略号:
Focus with soft study music in
the background and make sure...
实际效果
文本显示省略号后仍继续展示剩余内容:
Focus with soft study music
in the background and make sure ...
it caters to all your needs.
所用代码
CSS代码
.text-tocut{ display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; width:170px; height: 60px; font-size: 13px; margin-bottom: 10px; }
HTML代码
<div class="sub-box"> <img class ="sub-image" src="thumbnails\c.jpg"> <img class="playsong-button" src="buttons\playsong-button.jpg"> <p class="sub-desc"> Instrumental Study </p> <p class="text-tocut"> Focus with soft study music in the background and make sure it caters to all your needs. </p> </div>
解决方法
核心问题出在你设置的固定高度height:60px——这个高度超出了两行文本的实际占用高度,导致容器还有空间显示剩余文本。按以下步骤修改即可解决:
移除固定高度
删除.text-tocut中的height:60px,让容器高度由内容自动撑开,-webkit-line-clamp才能正确识别行数并完成截断。清除干扰样式
检查父元素或继承的样式,确保没有overflow: visible、white-space: nowrap这类属性干扰截断逻辑;如果有,给.text-tocut明确设置white-space: normal。无需使用
text-overflowtext-overflow: ellipsis仅对单行文本生效,多行截断完全依赖display: -webkit-box、-webkit-line-clamp、-webkit-box-orient: vertical这三个属性,不用额外添加。
修改后的CSS代码:
.text-tocut{ display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; width:170px; font-size: 13px; margin-bottom: 10px; white-space: normal; /* 确保无继承样式干扰 */ }
这样就能实现两行后截断并显示省略号的预期效果了。
内容的提问来源于stack exchange,提问作者Bhavani

