CSS 文本装饰
CSS 文本装饰详解 · 难度:入门 · +10XP
CSS 文本装饰详解
text-decoration 用于为文本添加装饰线,如下划线、上划线、删除线等。它是一个简写属性,包含了 text-decoration-line、text-decoration-color、text-decoration-style 和 text-decoration-thickness。
基本装饰线 text-decoration-line
设置装饰线的位置:
a {
text-decoration-line: underline; /* 下划线 */
}
.check {
text-decoration-line: line-through; /* 删除线(贯穿线) */
}
.overline {
text-decoration-line: overline; /* 上划线 */
}
.none-style a {
text-decoration-line: none; /* 去掉装饰线 */
}
完整简写 text-decoration
在一行中设置所有装饰属性:
/* text-decoration: line color style thickness */
a {
text-decoration: underline #3498db solid 2px;
}
/* 常用组合 */
.standard-link { text-decoration: underline; }
.no-underline { text-decoration: none; }
.strikethrough { text-decoration: line-through; }
.fancy-underline {
text-decoration: underline wavy #e74c3c 2px;
}
.dotted-link {
text-decoration: underline dotted #2980b9;
}
.thick-underline {
text-decoration: underline #2c3e50 3px;
}
装饰线颜色 text-decoration-color
可以单独设置装饰线的颜色,与文字颜色不同:
p {
color: #333;
text-decoration: underline;
text-decoration-color: #e74c3c; /* 红色下划线,但文字是深灰色 */
}
/* 使用 currentColor 将装饰线颜色与文字同步 */
a {
color: #3498db;
text-decoration: underline currentColor;
}
装饰线样式 text-decoration-style
| 值 | 效果 | 示例 |
|---|---|---|
| solid | 实线 | 标准下划线 |
| double | 双线 | 强调性下划线 |
| dotted | 点线 | 辅助性标注 |
| dashed | 虚线 | 临时性标记 |
| wavy | 波浪线 | 拼写或语法错误指示 |
.solid { text-decoration-style: solid; }
.double { text-decoration-style: double; }
.dotted { text-decoration-style: dotted; }
.dashed { text-decoration-style: dashed; }
.wavy { text-decoration-style: wavy; } /* 波浪线,常用于拼写检查 */
装饰线粗细 text-decoration-thickness
a {
text-decoration-thickness: 2px; /* 像素值 */
text-decoration-thickness: auto; /* 默认粗细(推荐) */
text-decoration-thickness: 0.1em; /* 相对字体大小 */
text-decoration-thickness: 10%; /* 百分比 */
}
/* 搭配应用 */
a.underline-none:hover {
text-decoration: underline #3498db solid 2px;
text-underline-offset: 4px; /* 下划线与文字间距 */
}
text-underline-offset 下划线偏移
text-underline-offset 控制下划线与文字之间的间距:
a {
text-decoration: underline;
text-underline-offset: 3px; /* 向下偏移 3px */
}
a:hover {
text-underline-offset: 6px; /* hover 时下划线远离文字 */
}
装饰线相关属性速查表
| 属性 | 作用 | 常用值 |
|---|---|---|
| text-decoration-line | 装饰线位置 | underline / overline / line-through / none |
| text-decoration-color | 装饰线颜色 | 任何 CSS 颜色值 |
| text-decoration-style | 装饰线样式 | solid / double / dotted / dashed / wavy |
| text-decoration-thickness | 装饰线粗细 | auto / 2px / 0.1em |
| text-underline-offset | 下划线偏移距离 | px / em / % |
| text-decoration | 简写属性 | underline red wavy 2px |
???? 练习
- 为不同链接设置不同样式的下划线(实线、虚线、波浪线)
- 使用 text-decoration-thickness 创建粗下划线强调效果
- 使用 text-underline-offset 调整链接下划线与文字的距离
- 创建一个 hover 时下划线从左滑入的动画效果
- 用 wavy 样式模拟拼写检查的红色波浪线标记