相对定位伪元素和绝对定位伪元素之间的差异

sha*_*lah 5 css

请考虑以下三种情况:

方案一:

div {
  width: 100px;
  height: 100px;
  background-color: black;    
}

div:before {
  content: "";
  width: 10px;
  height: 10px;
  background-color: darkred;
  position: relative;
}
Run Code Online (Sandbox Code Playgroud)

方案二:

div {
  width: 100px;
  height: 100px;
  background-color: black;    
}

div:before {
  content: "";
  width: 10px;
  height: 10px;
  background-color: darkred;
  position: absolute;
}
Run Code Online (Sandbox Code Playgroud)

方案三:

div {
  width: 100px;
  height: 100px;
  background-color: black;    
}

div:before {
  content: "";
  width: 10px;
  height: 10px;
  background-color: darkred;
  display:block;
  position: relative;
}
Run Code Online (Sandbox Code Playgroud)

方案一(相对位置)未显示darkred伪元素。但是当它变成position:absolute伪元素时,它是可见的。另外,如方案三所示,当我display:block向方案一(相对位置)添加属性时,该元素可见。

为什么relative职位需要display:blockabsolute不是?

jac*_*arm 10

诸如此类的伪类:before的默认displayCSS 属性值为inline.

默认情况下是display: inline;position: relative;不是“块级”元素的元素,如果它们没有内容,它们不占用任何宽度。因此,如果您没有声明display: block;并且您有一个空的内容声明,例如content: "";,它在场景 1 中根本不会占用任何宽度。

被元件position: absolute;采取流出来,并且与一个默认的“块级”元素display的CSS属性值block。因此,场景 2 呈现:before伪元素,遵守其宽度和高度声明。

场景 3 是成功的,因为该display属性已显式设置为block,这符合宽度和高度声明。

您可以通过检查:before浏览器的 Web 开发人员工具中的元素来查看这些默认值的设置- 请参阅工具的“元素”检查器。