在伪元素未显示之前

时间:2018-04-24 19:22:23

标签: html css

    div {
        width: 100px;
        height: 100px;
        background: red;
        }
    div:before {
        content: "";
        width: 100px;
        height:30px;
        background: yellow;
    }

为什么当没有设置位置值(相对和绝对值)时,前面的伪元素是否显示在div元素之上?

3 个答案:

答案 0 :(得分:4)

默认情况下,::before::after个伪元素为display:inlinewidthheight不会影响。

您可以将伪元素设置为display:block



div {
  width: 100px;
  height: 100px;
  background: red;
}

div:before {
  content: "";
  display: block;
  width: 100px;
  height: 30px;
  background: yellow;
}

<div></div>
&#13;
&#13;
&#13;

View on JSFiddle

另见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

&#13;
&#13;
 div {
  width: 100px;
  height: 100px;
  background: red;
}

div:before {
  content: "";
  width: 100px;
  height:30px;
  background: yellow;
  position: absolute;
}
&#13;
<div></div>
&#13;
&#13;
&#13;