日期:2014-05-16  浏览次数:20600 次

文字“中间划线”的几种CSS实现

写在前面的话,今天中秋假期最后一天,明天又得开始苦逼的生活了,在地铁上看到一篇文本“中间划线”

的微博,有点时间测试下,增长点小知识。
1)首先来看看text-decoration这个属性
可能的属性值:

浏览器支持如下图:

所有主流浏览器都支持 text-decoration 属性。
注释:任何的版本的 Internet Explorer (包括 IE8)都不支持属性值 "inherit"。
注释:IE、Chrome 或 Safari 不支持 "blink" 属性值。

平常在开发中接触最多的就是a标签的样式text-decoration:underline,或者text-decoration:none;

2)再来看看CSS3.0中的text-decoration-style属性:
可取值:
text-decoration-style: solid
text-decoration-style: double
text-decoration-style: dotted
text-decoration-style: dashed
text-decoration-style: wavy  //波浪效果
text-decoration-style: inherit

浏览器支持如下图:

demo01:
<style type="text/css">
	.line-through{ 
		text-decoration:line-through; 
		-moz-text-decoration-color:#f00; 
		-moz-text-decoration-style:double;
		-webkit-text-decoration-color:#f00; //chrome 24.0 开始支持
		-webkit-text-decoration-style:solid;//chrome 24.0 开始支持
	}
</style>
</head>
<body>
<p class="line-through">mydemo 我的Demo</p>
</body>

3)下面利用伪元素::before,::after来实现中间划线:

demo02:
<style type="text/css">
.line-through{
    position: relative;
    display: inline-block;
	width:100px;
	word-break:break-all;
	border:1px solid #f00;
}
.line-through::before {
    content: '';
    border-bottom: 2px solid #00f;
    width: 100%;
    position: absolute;
    right: 0;
    top: 50%;
}
</style>
</head>
<body>
<p class="line-through">mydemo 我的Demo</p>
</body>

此方法的局限性:不适用于多行文本

4)用::before 和 ::after以及CSS变换(transform)来创建一个文本上的交叉效果:

<style type="text/css">
.line-through {
    position: relative;
    display: inline-block;
}
.line-through::before, .line-through::after {
    content: '';
    width: 100%;
    position: absolute;
    right: 0;
    top: 50%;
}
.line-through::before {
    border-bottom: 2px solid #00f;
    -webkit-transform: skewY(-10deg);
    transform: skewY(-10deg);
}
.line-through::after {
    border-bottom: 2px solid #f00;
    -webkit-transform: skewY(10deg);
    transform: skewY(10deg);
}
</style>
</head>
<body>
<p class="line-through">mydemo 我的Demo</p>
</body>


效果如下图:

PS:我们还可以去掉变换,利用top值和边框实现double线的效果以及其他效果。@ME