好的,我们来系统梳理一下 CSS 的 text-decoration 属性,并附带实用示例和小技巧,方便你在网页设计中直接应用。
CSS text-decoration 属性详解
text-decoration 用于设置文本装饰,例如:下划线、删除线、上划线等。
它既可以单独设置,也可以组合多个效果。
一、语法
/* 简单用法 */
text-decoration: none | underline | overline | line-through | blink;
/* 复合写法(CSS3) */
text-decoration: <line> || <style> || <color>;
属性值解释:
| 值 | 说明 |
|---|---|
none | 不显示任何文本装饰(默认) |
underline | 下划线 |
overline | 上划线 |
line-through | 删除线 |
blink | 闪烁(现代浏览器基本不支持) |
initial | 默认值 |
inherit | 继承父元素值 |
CSS3 新增复合写法:
text-decoration: underline solid red;
- line:underline / overline / line-through / none
- style:solid / dotted / dashed / wavy / double
- color:颜色值,如 red / #ff0000 / rgb(255,0,0)
注意:复合写法可以一次性设置线型、样式和颜色,比以前的单一值更灵活。
二、单独属性(CSS3 拆分)
为了更灵活控制,CSS3 将 text-decoration 拆成三个子属性:
| 属性 | 作用 |
|---|---|
text-decoration-line | 设置线条类型:underline / overline / line-through / none |
text-decoration-style | 设置线条样式:solid / double / dotted / dashed / wavy |
text-decoration-color | 设置线条颜色 |
text-decoration-thickness | 设置线条粗细(px 或关键字 auto / from-font) |
三、实用示例
1️⃣ 下划线
a {
text-decoration: underline;
}
2️⃣ 删除线
del {
text-decoration: line-through;
}
3️⃣ 上划线 + 红色 + 虚线
h1 {
text-decoration-line: overline;
text-decoration-style: dashed;
text-decoration-color: red;
}
或者复合写法:
h1 {
text-decoration: overline dashed red;
}
4️⃣ 多重线条
p {
text-decoration-line: underline overline;
text-decoration-style: solid;
text-decoration-color: blue;
}
5️⃣ 移除默认链接下划线
a {
text-decoration: none;
}
四、实用小技巧
- 鼠标悬停显示下划线
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
- 动画删除线
del {
position: relative;
}
del::after {
content: "";
position: absolute;
left: 0;
bottom: 50%;
width: 0;
height: 2px;
background: red;
transition: width 0.3s;
}
del:hover::after {
width: 100%;
}
- 结合字体粗细自适应
h2 {
text-decoration-thickness: from-font;
}
线条厚度会跟随字体大小自动调整,更美观。
五、总结
text-decoration是文本装饰的核心属性,既可简单设置,也可 CSS3 高级复合控制。- CSS3 拆分属性提供更精准的控制:线条类型、样式、颜色、粗细。
- 可以结合 伪元素 或 动画,实现更炫酷的视觉效果。
发表回复