在伪元素未显示之前

Lea*_*ath 2 html css

    div {
        width: 100px;
        height: 100px;
        background: red;
        }
    div:before {
        content: "";
        width: 100px;
        height:30px;
        background: yellow;
    }
Run Code Online (Sandbox Code Playgroud)

当位置值(分别为相对值和绝对值)未设置时,为什么 before 伪元素没有显示在 div 元素上方?

sho*_*dev 7

::before::after伪元素是display:inline在默认情况下,这widthheight不会影响。

您可以将伪元素设置为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)

在 JSFiddle 上查看

另请参阅:before 和 :after 伪元素的默认显示属性是什么?


j08*_*691 5

默认情况下两者的显示性能: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)

jsfiddle 示例