我们经常会看到有些网站比较长的字符就会显示省略号了,实现这种效果有两个办法,一种利用程序截取字符,另一种利用css实现超出部分显示省略号,下面我来介绍第二种。
测试浏览器: IE6/7/8/9、opera12.02、firefox15.0.1、chrome
代码如下
复制代码
<p style="width:200px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">省略我吧 省略我吧! 省略我吧!省略我! </p>
如果我们要给p标签定义text-overflow:ellipsis就可以这么写:
代码如下
复制代码
p {
white-space: nowrap;
width: 100%;/* IE6 需要定义宽度 */
overflow: hidden;
-o-text-overflow: ellipsis;/* Opera */
text-overflow:ellipsis;/* IE, Safari (WebKit) */
}
现在解释一下为什么要这样做:
1、text-overflow: ellipsis;
这里的重点样式是text-overflow: ellipsis;
不过话说text-ellipsis是一个特殊的样式,有关解释是这样的:text-overflow属性仅是注解,当文本溢出时是否显示省略标记。并不具备其它的样式属性定义。要实现溢出时产生省略号的效果还须定义:强制文本在一行内显示(white-space:nowrap)及溢出内容为隐藏(overflow:hidden),只有这样才能实现溢出文本显示省略号的效果。简单理解就是我要把文本限制在一行(white-space: nowrap;),肯定这一行是有限制的(width),并且你的溢出的部分要隐藏起来(overflow: hidden;),然后出现省略号( text-overflow: ellipsis)。
2、white-space
顺便解释一下white-space的用法
white-space属性声明建立布局过程中如何处理元素中空白符。(废话一句,这里的空白符应该指我们用键盘敲入的空格或回车,因为用 或<br>无论white-space设置什么都会有空格或回车。)
完全实例
代码如下
复制代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>省略号 test</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
body{
padding:10px;
font-family:Arial;
}
#test {
position:relative;
width:150px;
height:20px;
line-height:20px;
text-overflow:ellipsis;
white-space:normal;
*white-space:nowrap;
overflow:hidden;
border:1px solid #999;
}
#test span{
position:absolute;
top:0;
right:0;
display:block;
float:left;
}
#test span:after{content:"...";}
</style>
</head>
<body>
<div id="test">小虾奋斗起来吧,加油加油加油加油加油加油<span></span></div>
</body>
</html>