text-overflow属性
这个属性针对那些在块级元素溢出的内容有效。
文本可能在以下情况下溢出:
- 由于某种原因无法换行,如设置了white-space:no-wrap
- 或者一个单词因为太长而不能被合理地安置
为了能让text-overflow属性生效,必须在元素上添加几个额外的属性:
- overflow:hidden
- white-space:no-wrap:不换行,只显示单行文本
text-overflow的几个取值:
- clip(默认值):超出的部分直接截断
ellipsis:超出的部分用省略号显示。这个省略号被添加在内容区域中,因此会减少显示的文本。如果空间太小到连省略号都容纳不下,那么这个省略号也会被截断。
自定义字符串(实验属性,大部分浏览器不支持):超出的部分用自定义字符串显示。字符串内容将被添加在内容区域中,所以会减少显示出的文本。如果空间太小到连字符串都容纳不下,那么这个字符串也会被截断。
<p class="overflow-visible">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
<p class="overflow-clip">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
<p class="overflow-ellipsis">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
p {
width: 200px;
border: 1px solid;
padding: 2px 5px;
/* BOTH of the following are required for text-overflow */
white-space: nowrap;
overflow: hidden;
}
.overflow-visible {
white-space: initial;
}
.overflow-clip {
text-overflow: clip;
}
.overflow-ellipsis {
text-overflow: ellipsis;
}
多行文本的溢出问题
text-overflow只能应用于单行文本的溢出处理。
有一个-webkit-line-clamp的实验属性貌似可以,但是搜不到什么资料。
可以使用伪元素来解决:
- 将height设为line-height的整数倍(要显示几行就设为几倍)
- 使用::after伪元素,绝对定位在元素的右下角。
- 可以给伪元素添加渐变背景避免遮盖文字。
- 要兼容ie6-7的话可以使用
<span>...</span>来完成
p{
line-height:20px;
height:60px;
overflow:hidden;
position:relative;
width:100px;
}
p::after{
content:"...";
position:absolute;
bottom:0;
right:0;
background:-webkit-linear-gradient(left,transparent,#fff 55%);
background:-o-linear-gradient(right,transparent,#fff 55%);
background:-moz-linear-gradient(right,transparent,#fff 55%);
background:linear-gradient(to right,transparent,#fff 55%);
}
本文介绍了如何使用CSS的text-overflow属性处理文本溢出问题,包括设置white-space、overflow及text-overflow的具体方法,并探讨了单行和多行文本溢出的解决方案。
5226

被折叠的 条评论
为什么被折叠?



