div {
width: 100px;
height: 100px;
background: red;
}
div:before {
content: "";
width: 100px;
height:30px;
background: yellow;
}
为什么当没有设置位置值(相对和绝对值)时,前面的伪元素是否显示在div元素之上?
答案 0 :(得分:4)
默认情况下,::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;
}

<div></div>
&#13;
另见What is the default display property of the :before and :after pseudo-elements?
答案 1 :(得分:3)
:before
和:after
的{{3}}显示属性是内联的,因此您的宽度和高度声明无效。将它改为阻止和鲍勃是你的叔叔:
div {
width: 100px;
height: 100px;
background: red;
}
div:before {
content: "";
display: block;
width: 100px;
height: 30px;
background: yellow;
}
<div></div>
<强> default 强>
答案 2 :(得分:1)
您忘了添加position:absolute
div {
width: 100px;
height: 100px;
background: red;
}
div:before {
content: "";
width: 100px;
height:30px;
background: yellow;
position: absolute;
}
&#13;
<div></div>
&#13;