:before和:after的作用就是在指定的元素内容(而不是元素本身)之前或者之后插入一个包含content属性指定内容的行内元素,最基本的用法如下:
<span style="font-size:18px;"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title></title>
<style>
#pid:before {
content: "*-*";
color: red;
}
#pid:after {
content: "!";
color: red;
}
</style>
</head>
<body>
<p id="pid">welcome to my home</p>
</body>
</html></span>
这段代码会在#pid元素内容之前插入一个'*-*',以及在内容之后添加一个'!',插入的行内元素是作为#pid的子元素,效果如下:
*-*welcome to my home!
如果没有content属性,伪类元素将没有任何作用。
但是可以指定content为空,插入的内容默认是一个行内元素,并且在HTML源代码中无法看到,这就是为什么称之为伪类元素的理由,所以也就无法通过DOM对其进行操作。
除了插入文字内容之外,还可以插入图片等。
转载请注明原文地址: https://ju.6miu.com/read-1307609.html