伪元素显示:块与显示:内联

时间:2020-07-04 10:07:46

标签: html css

我目前正在通过跟随freecodecamp.org的Youtube教程来练习CSS

我的代码如下:

p::before{
  content: "hello ";
  color: white;
  font-size: 60px;
  background: salmon;
  margin-bottom: 20px;
}

p::after{
  display: block;
  content: "";
  height: 100px;
  width: 100px;
  background: green;
}
<p>Before and after pseudo elements</p>

现在,当我在伪选择器之后指定display :: p ::中的块时,我将得到预期的输出,如下所示:

enter image description here

但是当我忽略display:block属性时,绿色框消失如下:

enter image description here

有人对此发生原因有适当的解释吗?我期望的是,该框仍将在“伪元素前后的hello”之后内联显示,但它完全消失了……

首先感谢您的帮助。

亲切的问候, Sohaib

2 个答案:

答案 0 :(得分:3)

然后使用display: inline-block

带有display: inline的元素不能设置明确的尺寸-这将无效。因此,由于伪元素没有非空内容,因此它将以0维出现,因此是不可见的。

答案 1 :(得分:0)

display: inline-block;添加到CSS

p::before{
  content: "hello ";
  color: white;
  font-size: 60px;
  background: salmon;
  margin-bottom: 20px;
}

p::after{
  display: inline-block;
  content: "";
  height: 100px;
  width: 100px;
  background: green;
}
<p>Before and after pseudo elements</p>