如何用 CSS 给文字加下划线
text-decoration: underline 在文字下方画一条线。除非你另外指定颜色,这条线会使用文字颜色。
第二行用 text-decoration 简写设置了线的类型、样式和颜色,再用各自的属性设置粗细和偏移。规范也允许把粗细写进简写,但只要写进去,Safari 就会丢弃整条声明,所以要单独写 text-decoration-thickness。
text-decoration 相关属性
| 属性 | 取值 | 默认值 |
|---|---|---|
text-decoration-line | underline、overline、line-through、none(可以组合) | none |
text-decoration-style | solid、double、dotted、dashed、wavy | solid |
text-decoration-color | 任意颜色 | currentColor(文字颜色) |
text-decoration-thickness | 长度、百分比、auto、from-font | auto |
text-underline-offset | 长度、百分比、auto | auto |
text-decoration 是前四个属性的简写,但不要把粗细写进去:Safari 会忽略包含粗细的 text-decoration 声明。text-underline-offset 是独立的,必须单独写。
样式、颜色和粗细
移动下划线:text-underline-offset
默认情况下,这条线紧贴着字母,遇到 g、p、y 这类下行字母时会断开绕过。text-underline-offset 能把它往下推,用在标题和链接上通常看起来更清爽:
下行字母周围的断口来自 text-decoration-skip-ink: auto,它默认开启。把它设为 none 就能得到一条连续的线。
去掉链接的下划线
链接的下划线来自浏览器的默认样式表。text-decoration: none 可以去掉它。因为很多读者靠下划线找链接,所以要在悬停和键盘聚焦时把它加回来,并给链接设置一个和正文不同的颜色:
导航栏和按钮可以去掉下划线,因为它们的位置本身就说明了“这是链接”。但在段落正文里,要保留下划线。关于链接状态的更多内容见 hover 页面。
上划线和删除线
text-decoration-line 也可以在文字上方或中间画线,并且可以接受多个值:
.old-price { text-decoration: line-through; }
.both { text-decoration-line: underline overline; }
用 CSS 画的删除线只是视觉效果。如果文字是被删除的内容(改过的价格、移除的条目),要像 HTML 下划线页面所示那样用 <s> 或 <del> 标记,让含义体现在标记里,而不只是体现在样式上。
常见错误
- 为了样式用
<u>加下划线。<u>用于标记与众不同的文字,比如拼写错误。要做带样式的下划线,用 CSS。 - 给不是链接的文字加下划线。读者会尝试点击它。要强调内容,改用粗体、颜色或背景。
- 去掉正文链接的下划线却没有提供其他提示。对分辨不出颜色差异的读者来说,只靠颜色是不够的。
- 试图在子元素上去掉父元素的下划线。无法从内部撤销;要么修改父元素,要么把子元素设为
inline-block。 - 以为
text-underline-offset能写进简写。它是一个独立的属性。 - 把粗细写进简写。
text-decoration: underline 2px在 Chrome 和 Firefox 中有效,但 Safari 会丢弃整条声明。使用text-decoration-thickness。
常见问题
如何用 CSS 给文字加下划线?
在元素上使用 text-decoration: underline;。要调整这条线的外观,再加上 text-decoration-color、text-decoration-style、text-decoration-thickness 和 text-underline-offset。
如何去掉链接的下划线?
在 a 元素上设置 text-decoration: none;。要确保链接仍能通过其他方式突出显示(颜色,加上悬停或获得焦点时的下划线),因为很多读者靠下划线来识别链接。
如何修改下划线的颜色?
使用 text-decoration-color,或者简写:text-decoration: underline #f59e0b;。不设置时,下划线使用文字颜色。
如何增加文字和下划线之间的距离?
使用 text-underline-offset,例如 text-underline-offset: 4px;。值越大,线离文字越远。
为什么无法去掉子元素上的下划线?
父元素画出的下划线会贯穿它的子元素,无法在子元素内部去掉。要在设置它的那个元素上去掉,或者把子元素设为 display: inline-block,父元素的装饰线不会作用到它。