DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 $200 免费积分!
CSS 中的 text-underline-offset
属性设置文本下划线与其初始位置之间的距离。
.element {
text-underline-offset: 0.5em;
}
使用 text-decoration
和 underline 值为元素应用下划线后,您可以使用 text-underline-offset
属性指定该线应与文本相距多远。
值
auto
: (默认)浏览器将为下划线指定适当的偏移量。<length>
: 任何有效的长度,带指定的单位(包括负值)。这将替换字体中的任何信息和浏览器默认设置。percentage
: 将下划线偏移量指定为元素字体中 1em 的百分比。initial
: 属性的默认设置,即 auto。inherit
: 采用父元素的下划线偏移值。unset
: 从元素中删除当前偏移量。
演示
在以下演示中,您可以更改 text-underline-offset
的值,以查看它如何影响元素的文本装饰。
笔记
text-underline-offset
不是text-decoration
的简写的一部分。- 它不适用于其他
text-decoration
行,例如line-through
或overline
。 - 接受负值,这会将下划线向内偏移。
它对后代是恒定的
为元素设置装饰后,其所有子元素也将具有该装饰。现在想象一下您想更改其中一个子元素的下划线偏移量。
p {
text-decoration: underline;
text-underline-offset: 0.5em;
}
p span {
text-underline-offset: 1.5em; /* Doesn't work */
}
这不起作用,因为您无法覆盖祖先元素指定的下划线偏移量。为了使此操作正常工作,您需要为该元素本身设置下划线特异性。
p {
text-decoration: underline;
text-underline-offset: 0.5em;
}
p span {
text-decoration: underline;
text-underline-offset: 1.5em; /* It works! */
}
建议使用 em
使用 em 等相对值的好处是,偏移量会随着 font-size
值的变化而缩放。另一方面,如果使用固定长度单位(例如像素),偏移量将不会调整以适应变化,它可能不是您希望文本具有的距离。
百分比和级联
对于此属性,长度将作为固定值继承,不会随字体缩放。另一方面,百分比将作为相对值继承,因此会随着字体变化而缩放,因为它会继承。
以下演示显示了在继承情况下使用 em 和百分比值之间的比较,正如您所看到的,在左侧(我们使用 em 的地方),继承的值是固定长度。您可以在 DevTools 中检查计算后的值。这意味着它不会随着字体的变化而缩放。但是,在右侧,文本继承了相对值(在本例中为 100%);因此偏移量会随着字体的变化而缩放。
书写模式和 text-underline-position
具有垂直书写模式会影响 下划线的位置。这将改变应用于元素的偏移方向。在以下演示中使用值进行尝试。
相关
更多信息
CSS 文本装饰模块级别 4 (编辑草案)
浏览器支持
在撰写本文时,Firefox 是唯一完全支持该属性的浏览器。Safari 不支持百分比值。
text-underline-offset
IE | Edge | Firefox | Chrome | Safari | Opera |
---|---|---|---|---|---|
否 | 否 | 70+ | 否 | 12.1+ | 全部 |
Android Chrome | Android Firefox | Android 浏览器 | iOS Safari | Opera Mini |
---|---|---|---|---|
否 | 否 | 否 | 12.2+ | 是 |
text-underline-offset: 百分比
IE | Edge | Firefox | Chrome | Safari | Opera |
---|---|---|---|---|---|
否 | 否 | 74+ | 否 | 否 | 否 |
Android Chrome | Android Firefox | Android 浏览器 | iOS Safari | Opera Mini |
---|---|---|---|---|
否 | 否 | 否 | 否 | 是 |
相关
text-decoration
.element { text-decoration: underline; }
text-decoration-line
.element { text-decoration-line: underline; }
text-decoration-thickness
.element { text-decoration-thickness: 2px; }
text-underline-offset
.element { text-underline-offset: 0.5em; }
text-underline-position
.element { text-underline-position: under; }