有一个例子。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
<title>An XHTML 1.0 Strict standard template</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<style>
DIV#outer {
display: inline-block;
width: 100px;
height: 100px;
background-color: blue;
}
DIV#inner {
display: inline-block;
width: 50px;
height: 50px;
background-color: green;
}
DIV#inner:before {
display: inline-block;
content: '123';
background-color: red;
}
</style>
</head>
<body>
<div id="outer">
<div id="inner">
</div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
'#inner:before' 伪元素在 '#inner' 内呈现。为了使其在外部渲染,我需要将最后一个 css 块中的选择器替换为“DIV#outer:before”,这样它将在“#outer”内部渲染,但在“#inner”之前。问题是为什么我会观察到这种行为?w3schools说“:before 选择器在所选元素之前插入内容”。在元素之前,但不在元素内容之前。
来自CSS 2.1 规范(添加了重点):
作者使用 :before 和 :after 伪元素指定生成内容的样式和位置。正如其名称所示, :before 和 :after 伪元素指定元素的文档树内容之前和之后内容的位置。