含HTML标签的div实现text-overflow: ellipsis效果的方法问询
问题原因
text-overflow: ellipsis 仅对单行文本生效,且必须配合 white-space: nowrap 使用。你的容器内包含多个块级元素(段落、列表),属于多行多结构内容,默认省略规则完全不适用,所以只会隐藏溢出内容,不会显示省略号。
解决方案
提供两种纯CSS实现方式,可根据兼容性需求选择:
方案1:全浏览器兼容(伪元素模拟省略号)
通过伪元素在容器右下角添加省略号,并用背景色覆盖溢出内容,不管内部是什么元素都能生效。
修改后的CSS代码:
.article-block { width: 92mm; height: 85mm; margin-top: 2mm; overflow: hidden; position: relative; background: #ffffff; /* 务必设置和页面背景一致的颜色 */ } .article-block::after { content: "..."; position: absolute; bottom: 0; right: 0; padding: 0 4px; /* 给省略号加左右内边距,避免和内容贴太近 */ background: inherit; /* 继承容器背景色,覆盖后面的溢出内容 */ }
注意点
如果容器内容没有溢出,省略号依然会显示。纯CSS无法完美实现“仅溢出时显示”的判断(需JS辅助),若默认内容大概率会溢出,可直接使用此方案。
方案2:WebKit内核专属(原生多行省略)
若只需兼容Chrome、Safari等WebKit内核浏览器,可使用原生多行省略特性,效果更精准(仅溢出时显示省略号)。
步骤1:修改HTML,给内部内容加一层包裹
<div class="article-block"> <div class="content-wrap"> <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. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p> <ul> <li>Some text #1</li> <li>Some text #2</li> <li>Some text #3</li> </ul> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p> </div> </div>
步骤2:添加对应CSS
.article-block { width: 92mm; height: 85mm; margin-top: 2mm; overflow: hidden; } .content-wrap { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 25; /* 根据容器高度调整最大行数,数值越大显示越多内容 */ overflow: hidden; text-overflow: ellipsis; }
注意点
-webkit-line-clamp 是WebKit私有属性,Firefox(版本68+)和IE不支持。
内容的提问来源于stack exchange,提问作者nphuly
相关产品推荐
相关产品推荐

