7.1 伪元素 ::first-letter
伪元素 ::first-letter
和 ::first-line
提供了强大的工具来对文本元素的首字母和首行进行样式化。这些伪元素广泛用于创建各种排版效果,以提高网页上的文本可读性和美感。
伪元素 ::first-letter
允许你为文本块的首字母设置样式。它常用于创建装饰效果,比如加大或设置特殊样式的段落首字母。
选择器::first-letter {
/* 样式 */
}
使用 ::first-letter 的示例
在这个示例中,段落的首字母被放大,加粗,并设置为蓝色。float: left
和 margin-right
属性创建了一个“嵌入”的首字母效果,推动其余文本:
/* 段落首字母的样式 */
p::first-letter {
font-size: 2em;
font-weight: bold;
color: #3498db;
float: left;
margin-right: 0.1em;
}
::first-letter 支持的属性
伪元素 ::first-letter
支持多种属性,包括:
font
color
background
margin
padding
border
float
text-transform
text-decoration
通过这些属性,你可以灵活地控制文本首字母的外观。
扩展的 ::first-letter 样式示例
在这个示例中,首字母增加了附加效果——文字阴影和更大的尺寸:
/* 带有附加效果的段落首字母样式 */
p::first-letter {
font-size: 3em;
font-weight: bold;
color: #e74c3c;
float: left;
margin-right: 0.2em;
line-height: 1;
text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
}
7.2 伪元素 ::first-line
伪元素 ::first-line
允许你为文本块的首行设置样式。它用于创建各种排版效果,比如改变首行的字体或颜色,改善文本的视觉效果。
语法:
选择器::first-line {
/* 样式 */
}
使用 ::first-line 的示例
在这个示例中,段落的首行被加粗,设成绿色,并配有浅灰色背景:
/* 段落首行的样式 */
p::first-line {
font-weight: bold;
color: #2ecc71;
background-color: #f0f0f0;
}
::first-line 支持的属性
伪元素 ::first-line
支持多种属性,包括:
font
color
background
margin
padding
border
line-height
text-transform
text-decoration
letter-spacing
word-spacing
这些属性允许你灵活地控制文本首行的外观。
扩展的 ::first-line 样式示例
在这个示例中,首行增加了附加效果,比如将文本转换为大写和改变字母间距与单词间距:
/* 带有附加效果的段落首行样式 */
p::first-line {
font-weight: bold;
color: #e67e22;
background-color: #f9f9f9;
text-transform: uppercase;
letter-spacing: 0.1em;
word-spacing: 0.2em;
}
7.3 组合使用 ::first-letter 和 ::first-line
伪元素 ::first-letter
和 ::first-line
可以结合使用,以创建复杂的排版效果。
组合使用的示例
在这个示例中,段落的首字母和首行被赋予了不同的样式,创造了复杂而有趣的视觉效果:
/* 段落首字母和首行的样式 */
p::first-letter {
font-size: 2.5em;
font-weight: bold;
color: #3498db;
float: left;
margin-right: 0.1em;
}
p::first-line {
font-weight: bold;
color: #2ecc71;
background-color: #f0f0f0;
}
完整示例
在这个示例中,段落的首字母被放大并设成蓝色,而首行被加粗并设成绿色,配有灰色背景:
/* 段落首字母的样式 */
p::first-letter {
font-size: 2.5em;
font-weight: bold;
color: #3498db;
float: left;
margin-right: 0.1em;
}
/* 段落首行的样式 */
p::first-line {
font-weight: bold;
color: #2ecc71;
background-color: #f0f0f0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>伪元素 ::first-letter 和 ::first-line 的示例</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam id dolor id nibh ultricies vehicula ut id elit. Curabitur blandit tempus porttitor. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Nullam quis risus eget urna mollis ornare vel eu leo.</p>
</body>
</html>
GO TO FULL VERSION