隐藏

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

发布:2020/11/9 17:28:47作者:管理员 来源:本站 浏览次数:1309

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

的微博,有点时间测试下,增长点小知识。
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

浏览器支持如下图:


  1. demo01:
  2. <style type="text/css">
  3. .line-through{
  4. text-decoration:line-through;
  5. -moz-text-decoration-color:#f00;
  6. -moz-text-decoration-style:double;
  7. -webkit-text-decoration-color:#f00; //chrome 24.0 开始支持
  8. -webkit-text-decoration-style:solid;//chrome 24.0 开始支持
  9. }
  10. </style>
  11. </head>
  12. <body>
  13. <p class="line-through">mydemo 我的Demo</p>
  14. </body>

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


  1. demo02:
  2. <style type="text/css">
  3. .line-through{
  4. position: relative;
  5. display: inline-block;
  6. width:100px;
  7. word-break:break-all;
  8. border:1px solid #f00;
  9. }
  10. .line-through::before {
  11. content: '';
  12. border-bottom: 2px solid #00f;
  13. width: 100%;
  14. position: absolute;
  15. right: 0;
  16. top: 50%;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <p class="line-through">mydemo 我的Demo</p>
  22. </body>

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

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


  1. <style type="text/css">
  2. .line-through {
  3. position: relative;
  4. display: inline-block;
  5. }
  6. .line-through::before, .line-through::after {
  7. content: '';
  8. width: 100%;
  9. position: absolute;
  10. right: 0;
  11. top: 50%;
  12. }
  13. .line-through::before {
  14. border-bottom: 2px solid #00f;
  15. -webkit-transform: skewY(-10deg);
  16. transform: skewY(-10deg);
  17. }
  18. .line-through::after {
  19. border-bottom: 2px solid #f00;
  20. -webkit-transform: skewY(10deg);
  21. transform: skewY(10deg);
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <p class="line-through">mydemo 我的Demo</p>
  27. </body>


效果如下图:

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