CSS 文本样式
学习 text-align/line-height/letter-spacing · 难度:入门 · +10XP
CSS 文本样式详解
CSS 提供了丰富的文本样式属性,让你能够控制网页中文字的颜色、对齐方式、装饰效果、间距等。掌握文本样式是网页设计的基础,好的文字排版能显著提升用户体验。
文本颜色 color
color 属性用于设置文本的颜色。颜色值可以是颜色名称(如 red)、十六进制值(如 #ff0000)、RGB 值(如 rgb(255,0,0))或 HSL 值。
p {
color: #333333;
}
h1 {
color: #1a73e8;
}
.highlight {
color: red;
}
文本对齐 text-align
text-align 控制文本在元素内的水平对齐方式。可选值有:left(左对齐)、right(右对齐)、center(居中)和 justify(两端对齐)。
h1 {
text-align: center;
}
p {
text-align: justify;
}
.right {
text-align: right;
}
文本装饰 text-decoration
text-decoration 是一个简写属性,可同时设置 text-decoration-line、text-decoration-color、text-decoration-style 和 text-decoration-thickness。
a {
text-decoration: none; /* 去掉下划线 */
}
del {
text-decoration: line-through;
}
.underline {
text-decoration: underline wavy #ff6600;
}
文本转换 text-transform
text-transform 用于控制字母的大小写转换。这在处理用户输入时特别有用。
p.uppercase {
text-transform: uppercase;
}
p.lowercase {
text-transform: lowercase;
}
p.capitalize {
text-transform: capitalize; /* 每个单词首字母大写 */
}
行高 line-height
line-height 设置行与行之间的高度。合理的行高能显著提升阅读体验,建议设置为字体大小的 1.5 到 2 倍。
body {
line-height: 1.6;
}
p.article {
font-size: 16px;
line-height: 1.8; /* 约 28.8px */
}
文本间距 letter-spacing 与 word-spacing
h2 {
letter-spacing: 2px; /* 字间距 */
}
p {
word-spacing: 5px; /* 词间距 */
}
常用文本属性速查表
| 属性 | 作用 | 常用值 | 示例 |
|---|---|---|---|
| color | 文本颜色 | 颜色值 | color: #333; |
| text-align | 水平对齐 | left/center/right/justify | text-align: center; |
| text-decoration | 文本装饰 | none/underline/line-through | text-decoration: none; |
| text-transform | 大小写转换 | uppercase/lowercase/capitalize | text-transform: uppercase; |
| line-height | 行高 | 数字或长度值 | line-height: 1.6; |
| letter-spacing | 字间距 | px/em | letter-spacing: 2px; |
| word-spacing | 词间距 | px/em | word-spacing: 4px; |
| white-space | 空白处理 | normal/nowrap/pre/pre-wrap | white-space: nowrap; |
| text-indent | 首行缩进 | px/em/% | text-indent: 2em; |
| word-break | 单词断行 | normal/break-all/keep-all | word-break: break-all; |
???? 练习
- 创建一个段落,设置颜色为深灰色,行高为 1.8,首行缩进 2em
- 为所有链接去掉下划线,并设置鼠标悬停时显示下划线
- 创建一个标题,使用 letter-spacing: 3px 使其更有设计感
- 使用 text-align: justify 让长段落两端对齐,观察效果差异
- 尝试用 text-transform 将一段英文全部转为大写并添加 letter-spacing