9

好消息,CSS text-underline-offset可以用起来了

 3 years ago
source link: https://www.zhangxinxu.com/wordpress/2021/02/css-text-underline-offset/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

byzhangxinxu from https://www.zhangxinxu.com/wordpress/?p=9857

本文欢迎分享与聚合,全文转载就不必了,尊重版权,圈子就这么大,若急用可以联系授权。

zIZbyqb.png!mobile

关于下划线和文字重叠的问题,就是下图所示的问题:

nmQbQbz.png!mobile

我以前专门写文章介绍过,详见:“ 解决文字和text-decoration:underline下划线重叠问题 ”。

里面介绍了N种解决方法。

现在,上面文章中的那些方法再也不需要了,因为浏览器提供了原生的解决方法,那就是 text-underline-offset 属性,随着Chrome 87开始完全支持,这个CSS属性可以用起来了。

一、text-underline-offset简介

text-underline-offset 属性可以用来设置下划线偏移位置。

这里有个demo,大家可以感受下效果,您可以狠狠地点击这里: text-underline-offset下划线偏移demo

拖动滑杆后,可以看到类似下图的下划线位置移动效果:

NbQfumZ.gif!mobile

语法

text-underline-offset 属性的语法如下:

text-underline-offset: auto | <length> | <percent>

其中:

auto 默认值。 <length> 长度值。 <percent> 百分比值。百分比是相对于1em大小计算的。因此, text-underline-offset:100% 等同于 text-underline-offset:1em

二、细节与特性说明

以下是几个细节特性。

  1. text-underline-offset 属性不是 text-decoration 的缩写属性之一,是独立的CSS属性。
  2. 只有下划线的时候 text-underline-offset 属性才有效,删除线和上划线都是无效的。例如下面两种下划线设置 text-underline-offset 属性是无效的:
    /* 应用text-underline-offset无效 */
    text-decoration: through;
    text-decoration: overline;
  3. text-decoration

    下划线效果具有父子元素互不干涉、同时累加的特性,因此,如果父元素设置了下划线,然后部分子元素的下划线位置偏移,则下面的CSS语句是无效的:

    p {
        text-decoration: underline;
        text-underline-offset: 0.5em;
    }
    p span {
        text-underline-offset: 1.5em; /* 无效 */
    }

    需要子元素明确声明具有下划线,例如:

    p {
        text-decoration: underline;
        text-underline-offset: 0.5em;
    }
    p span {
        text-decoration: underline;
        text-underline-offset: 1.5em; /* 有效 */
    }

兼容性

目前 text-underline-offset 属性所有现代浏览器均已支持,由于本身就属于渐进增强特性,因此,可以在实际项目中放心使用。

具体兼容性参见下面截图:

NZv6Jfb.png!mobile

可以看到,距离我写下这篇文章,Chrome支持不过数月时间,所以标题才说“好消息”,毕竟现在是Chrome的天下。

三、结语

目前,下划线的颜色、样式(例如波浪线)、位置等都有对应的CSS属性可以设置,详见我多年前介绍的这篇文章:“ 了解CSS3 text-decoration波浪线等新特性 ”。

好,关于 text-underline-offset 属性其他就没有什么好说的了。

感谢您的阅读,欢迎补充更多关于 text-underline-offset 属性的信息。

BnyAV3B.png!mobile

本文为原创文章,欢迎分享,勿全文转载,如果实在喜欢,可收藏,永不过期,且会及时更新知识点及修正错误,阅读体验也更好。

本文地址: https://www.zhangxinxu.com/wordpress/?p=9857

(本篇完)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK