div {
width: 100px;
height: 100px;
background: red;
}
div:before {
content: "";
width: 100px;
height:30px;
background: yellow;
}
Run Code Online (Sandbox Code Playgroud)
当位置值(分别为相对值和绝对值)未设置时,为什么 before 伪元素没有显示在 div 元素上方?
在::before和::after伪元素是display:inline在默认情况下,这width并height不会影响。
您可以将伪元素设置为display:block.
div {
width: 100px;
height: 100px;
background: red;
}
div:before {
content: "";
display: block;
width: 100px;
height: 30px;
background: yellow;
}Run Code Online (Sandbox Code Playgroud)
<div></div>Run Code Online (Sandbox Code Playgroud)
另请参阅:before 和 :after 伪元素的默认显示属性是什么?
在默认情况下两者的显示性能:before和:after是内联,所以你的宽度和高度声明没有任何效果。将其更改为阻止并且 bob 是您的叔叔:
div {
width: 100px;
height: 100px;
background: red;
}
div:before {
content: "";
display: block;
width: 100px;
height: 30px;
background: yellow;
}Run Code Online (Sandbox Code Playgroud)
<div></div>Run Code Online (Sandbox Code Playgroud)