CSS 中如何为文本添加下划线?

17 Mar 2025 | 4 分钟阅读

CSS 文本装饰(Text-decoration)属性:-

下划线可用于突出显示重要文本。U 元素和 CSS 的 text-decoration 属性是在网页上为文本添加下划线的两种最常用的技术。

两者都易于使用,但 U 元素提供了语义价值。另一种可以在需要时显示,通过简单地将 CSS 类添加到文本即可轻松更改下划线状态。

下划线是否对表达意义或可访问性有用是一个有争议的问题。当仅凭颜色不足以表达意义时,下划线是一种提供更好用户体验的自然方法。

text-decoration 属性提供了一种为文本添加下划线的替代方法。超链接文本也可用于将下划线替换为上划线。

上划线是下划线的反面。即在文本顶部添加一条线。

我们可以为同一个类定义使用所有下划线和上划线的值。text-decoration 属性以多种方式控制文本的显示方式。当 text-decoration 设置为 underline 时,组件内的文本将显示下划线。

Text decoration CSS 属性对于文本非常棒,但在设计方面可能受到限制,并且不适用于非文本内容类型。下划线也可以使用 CSS 的 border 属性来创建。

text-decoration 属性是为文本添加下划线的最基本方法。text decoration 的最大缺点是它不可配置。

text-decoration 属性使用下划线、上划线、删除线或这些线的组合来突出显示选定的文本。

使用 text-decoration-line 属性为内容添加下划线。此属性有三种选项:overline(上划线)、underline(下划线)和 line-through(删除线)。在 CSS 中,使用 underline 属性来突出显示文本。使用此值,下划线将绘制在内联文本的下方。

文本装饰会绘制在所有后代文本元素上。这意味着当一个元素定义了文本装饰时,子元素无法移除该装饰。

不绘制任何线条,并且会删除任何现有的装饰。

Underline(下划线):在文本基线上绘制一条 1px 的线。

Line-through(删除线):在文本的“中心”点,在其上方绘制一条 1px 的线。

Overline(上划线):在文本的“顶部”点上方直接绘制一条 1px 的线。

Inherit(继承):继承父元素的装饰。

文本装饰通过 text-decoration 属性指定,该属性是以下属性的简写:

  • text-decoration-line(必需)
  • text-decoration-color
  • text-decoration-style
  • text-decoration-thickness

overline、underline、underline-overline、line-through 属于 text-decoration-line。

Solid(实线)、dotted(点线)、dashed(虚线)、wavy(波浪线)、double(双线)属于 text-decoration-style。

Color(颜色)可以是十进制值、十六进制值或 inherit。

border-bottom 属性是 text decoration 的替代方法。我们还可以使用 border-bottom 来提供内边距(padding)。

语法:-

现在,让我们看一个示例,了解 text-decoration 属性的用法。

Text-decoration: underline overline

示例:-

输出

How to underline text in CSS?

上面的示例用于演示使用 underline 和 underline overline 的 text-decoration 属性。

Text-decoration: underline

示例:-

输出

How to underline text in CSS?

上面的示例显示了 text-decoration 属性中 underline 的用法。

Text-decoration: line-through

示例:-

输出

How to underline text in CSS?

Text-decoration-color

示例:-

输出

How to underline text in CSS?

Text-decoration-style

示例:-

输出

How to underline text in CSS?
下一主题CSS 弹跳效果