6.1 属性 content
伪元素 ::before
和 ::after
允许在元素内容的前后添加内容,而无需更改HTML代码。
它们广泛用于装饰目的、改善用户界面并创建更互动的网页。
什么是伪元素 ::before 和 ::after?
伪元素 ::before
和 ::after
创建虚拟元素,分别在所选元素的内容之前和之后插入。
这些伪元素常用于添加图标、装饰性元素或其他视觉效果。
before 语法:
选择器::before {
content: "文本或其他值";
/* 样式 */
}
after 语法:
选择器::after {
content: "文本或其他值";
/* 样式 */
}
属性 content
对于伪元素 ::before
和 ::after
的关键属性是 content
。该属性定义了伪元素的内容。
它可以是文本字符串、图像,甚至是空值,如果只需要视觉效果。
属性 content 的可能值:
- 文本:
"文本"
- 图像:
url("path/to/image.png")
- 空值:
""
- 属性:
attr(attributeName)
- 计数器:
counter(name)
6.2 ::before 和 ::after 的使用示例
添加装饰元素
示例 1: 在文本前添加图标
在这个例子中,伪元素 ::before
用于在链接文本前添加图标。
margin-right
添加了图标和文本之间的空间:
/* 在链接文本前添加图标 */
a::before {
content: "🔗";
margin-right: 5px;
}
示例 2: 在段落后添加装饰元素
在这个例子中,伪元素 ::after
在段落后添加了一个装饰元素。display: block
和
text-align: right
用于将元素对齐到右边:
/* 在段落后添加装饰元素 */
p::after {
content: "❦";
display: block;
text-align: right;
color: red;
}
创建装饰性的边框和背景
示例 3: 元素周围的装饰性边框
在这个例子中,伪元素 ::before
用于创建一个装饰条在
div
元素上方。position: absolute
和 top: -10px
允许将条定位于元素上方:
/* 元素周围的装饰性边框 */
div::before {
content: "";
display: block;
width: 100%;
height: 10px;
background-color: #3498db;
position: absolute;
top: -10px;
left: 0;
}
示例 4: 自动添加引号
在这个例子中,伪元素 ::before
和 ::after
用于在引用块周围自动添加引号:
/* 自动添加引号到引用块周围 */
blockquote::before {
content: "“";
font-size: 2em;
color: #ccc;
}
blockquote::after {
content: "”";
font-size: 2em;
color: #ccc;
}
示例 5: 标题编号
在这个例子中,伪元素 ::before
用于在 h2
标题前添加数字。
counter-increment
增加计数器值,而 content: counter(section)
插入当前计数器值:
/* 标题编号 */
h2::before {
counter-increment: section;
content: counter(section) ". ";
font-weight: bold;
}
6.3 伪元素的应用和样式化
伪元素的样式化
伪元素可以像其他元素一样进行样式化。它们支持大多数CSS属性,包括颜色、背景、边框、大小和定位。
使用伪元素创建复杂布局
伪元素常用于在布局中创建装饰元素,如边框、阴影和其他视觉效果,而无需添加额外的HTML元素。
示例: 每个列表项会在文本前有一个蓝色标记:
ul li::before {
content: "•";
color: blue;
margin-right: 5px;
}
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
6.4 完整实现的示例
/* 在链接文本前添加图标 */
a::before {
content: "🔗";
margin-right: 5px;
}
/* 在段落后添加装饰元素 */
p::after {
content: "❦";
display: block;
text-align: right;
color: red;
}
/* 元素周围的装饰性边框 */
.decorative-box {
position: relative;
}
.decorative-box::before {
content: "";
display: block;
width: 100%;
height: 10px;
background-color: #3498db;
position: absolute;
top: -10px;
left: 0;
}
/* 自动添加引号到引用块周围 */
blockquote::before {
content: "“";
font-size: 2em;
color: #ccc;
}
blockquote::after {
content: "”";
font-size: 2em;
color: #ccc;
}
/* 标题编号 */
h2::before {
counter-increment: section;
content: counter(section) ". ";
font-weight: bold;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>伪元素 ::before 和 ::after 示例</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<a href="#">带图标的链接</a>
<p>文本后有装饰元素的段落</p>
<div class="decorative-box">带装饰框的元素</div>
<blockquote>带自动引号的引用</blockquote>
<h2>带编号的标题</h2>
<h2>另一个标题</h2>
</body>
</html>
GO TO FULL VERSION