
CSS文本溢出处理:巧妙截断过长文本并显示省略号
网页设计中,文本内容超出容器的情况十分常见。本文将介绍如何使用CSS优雅地解决这个问题,避免文本溢出导致页面显示混乱。我们将通过示例讲解单行文本和多行文本溢出的两种CSS解决方案。
问题: 一个<div>元素内容过长,超出预设宽度,导致文本全部显示,而我们希望超出部分被截断并显示省略号(...)。
<p>示例代码:</p>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p>
<pre class="brush:php;toolbar:false;"><div class="box-container py-5">
<div class="content">
testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest
</div>
</div></pre>
<pre class="brush:php;toolbar:false;">#demo .content {
width: 300px;
border: 1px solid red;
}</pre>
<p><strong>解决方案:</strong></p>
<p><strong>1. 单行文本溢出:</strong></p>
<p>使用以下CSS属性组合:</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/2284" title="Insou AI"><img
src="https://img.php.cn/upload/ai_manual/001/246/273/68b6b92f7dac5391.png" alt="Insou AI" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/2284" title="Insou AI">Insou AI</a>
<p>Insou AI 是一款强大的人工智能助手,旨在帮助你轻松创建引人入胜的内容和令人印象深刻的演示。</p>
</div>
<a href="/ai/2284" title="Insou AI" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>
<pre class="brush:php;toolbar:false;">.content {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}</pre>
<ul>
<li>
<code>overflow: hidden; 隐藏溢出内容;
white-space: nowrap; 防止文本换行;text-overflow: ellipsis; 在文本末尾显示省略号。这三个属性配合使用,可完美解决单行文本溢出问题。
2. 多行文本溢出:
可以使用以下方法:
.content {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2; /* 设置显示行数,超出部分显示省略号 */
overflow: hidden;
text-overflow: ellipsis;
}
这段代码利用了-webkit-box相关的属性。-webkit-line-clamp属性指定允许显示的行数,超出部分将以省略号代替。请注意,此方法主要兼容WebKit内核浏览器(例如Chrome和Safari)。 overflow: hidden; 和 text-overflow: ellipsis; 仍然是必要的。 通过修改-webkit-line-clamp的值,可以控制显示的行数。
通过以上方法,您可以有效地处理CSS文本溢出问题,使您的网页布局更加美观和整洁。









