必须设置content属性才能生效,::before和::after用于在元素前后插入装饰性内容,如引号、图标、分隔符等,不影响文档结构仅用于视觉效果,可结合样式实现复杂设计。

CSS 的 ::before 和 ::after 伪元素用于在元素的内容之前或之后插入装饰性内容,通常配合 content 属性使用。它们不会影响文档结构,只在渲染层添加视觉效果,适合做图标、引号、分隔符等装饰。
要使用这两个伪元素,必须设置 content 属性,即使为空也要写成 content: "";,否则伪元素不会生效。
.element::before {
content: "★";
color: gold;
}
.element::after {
content: " (注)";
color: gray;
}
上面代码会在 .element 内容前加一个星号,后面加“ (注)”灰色文字。
以下是一些实用的装饰场景:
立即学习“前端免费学习笔记(深入)”;
blockquote::before {
content: "“";
font-size: 1.5em;
color: #888;
}
blockquote::after {
content: "”";
font-size: 1.5em;
color: #888;
}
.link::after {
content: " →";
color: blue;
}
.list-item:not(:last-child)::after {
content: " | ";
color: #ccc;
}
伪元素不只是插文字,还能通过 CSS 样式做出更复杂的装饰,比如背景、边框、定位等。
.tip::before {
content: "!";
display: inline-block;
width: 16px;
height: 16px;
background-color: #007acc;
color: white;
text-align: center;
border-radius: 50%;
margin-right: 8px;
font-weight: bold;
}
这样就在提示文字前创建了一个小圆形图标,提升可读性和美观度。
基本上就这些。只要记得 必须写 content,然后就可以自由发挥添加各种装饰内容。不复杂但容易忽略细节。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号