我们可以设置元素的特定部分的样式,例如第一个字母、第一行,甚至在其之前/之后插入。为此,使用 css 伪元素。
注意 - 为了将 CSS 伪类与伪元素分开,在 CSS3 中,伪元素使用双冒号表示法。
语法以下是在元素上使用 CSS 伪元素的语法 -
Selector::pseudo-element {
css-property: /*value*/;
}以下是所有可用的 CSS 伪元素 -
| Sr.No | 伪元素和描述 |
|---|---|
| 1 |
after 在内容之后插入一些内容每个提到的元素 立即学习“前端免费学习笔记(深入)”; |
| 2 |
之前 插入每个提到的元素的内容之前的内容 |
| 3 |
第一个字母 它选择每个提到的元素的第一个字母 |
| 4 | first-line strong> 它选择每个提到的元素的第一行 |
| 5 |
placeholder 它选择表单元素中的占位符文本 |
| 6 | selection 它选择用户选择的元素部分 |
让我们看一个 CSS 伪元素的示例 -
现场演示
<!DOCTYPE html>
<html>
<head>
<style>
p::first-letter {
background-color: black;
}
p::first-line {
background-color: lightgreen;
color: white;
}
span {
font-size: 2em;
color: #DC3545;
}
</style>
</head>
<body>
<h2>Computer Networks</h2>
<p><span>A</span> system of interconnected computers and computerized peripherals such as printers is called computer network. </p>
</body>
</html>让我们看看 CSS 伪元素的另一个示例 -

实时演示
<!DOCTYPE html>
<html>
<head>
<style>
div:nth-of-type(1) p:nth-child(2)::after {
content: " LEGEND!";
background: orange;
padding: 5px;
}
div:nth-of-type(2) p:nth-child(2)::before {
content: "Book:";
background-color: lightblue;
font-weight: bold;
padding: 5px;
}
</style>
</head>
<body>
<div>
<p>Cricketer</p>
<p>Sachin Tendulkar:</p>
</div>
<hr>
<div>
<p><q>Chase your Dreams</q></p>
<p><q>Playing It My Way</q></p>
</div>
</body>
</html>
以上就是CSS 伪元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号