为什么 width/height 不能用于非定位伪元素?

Why doesn't width/height work with non positioned pseudo elements?

我想将 ::before 伪元素的 width 设置为 80%。如果我使用定位那么一切正常,但如果我不使用它那么一切都会失败。

你能解释一下为什么百分比宽度在没有定位的情况下不起作用吗?如果可以,请添加一些对规范的引用

.positioned {
    position: relative;
    height: 15px;
    background-color: aquamarine;
    margin-bottom: 10px;
}
.positioned::before {
    position: absolute;
    content: "";
    background: red;
    width: 80%;
    height: 100%;
}

.not-positioned {
    height: 15px;
    background-color: aquamarine;
    margin-bottom: 10px;
}
.not-positioned::before {
    content: "";
    background: red;
    width: 80%;
    height: 100%;
}
<div class="positioned"></div>
<div class="not-positioned"></div>

首先,这与百分比值无关。即使像素值和宽度和高度都不起作用,您也会得到相同的结果。

伪元素是内联元素,其width/height仅由其内容定义,width/height设置为CSS将被忽略.

In CSS, ::before creates a pseudo-element that is the first child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default. ref

width

This property does not apply to non-replaced inline elements. The content width of a non-replaced inline element's boxes is that of the rendered content within them ref

The 'height' property does not apply. The height of the content area should be based on the font ... ref


通过创建伪元素 position:absolute,您现在将考虑适用于 Absolutely positioned element 的规则来计算宽度和高度。您还会注意到该元素在 display.

中的计算值为 block

你还应该注意 positioned element 的使用,这意味着 relative, absolute, fixed or sticky 但使元素 position:relative 将保持内联level 元素,你仍然不能使用 width/height.

.positioned {
    position: relative;
    height: 15px;
    background-color: aquamarine;
    margin-bottom: 10px;
}
.positioned::before {
    position: relative;
    content: "";
    background: red;
    width: 80%;
    height: 100%;
}

.not-positioned {
    height: 15px;
    background-color: aquamarine;
    margin-bottom: 10px;
}
.not-positioned::before {
    content: "";
    background: red;
    width: 80%;
    height: 100%;
}
<div class="positioned"></div>
<div class="not-positioned"></div>

这就是说,如果您想获得相同的视觉效果,可以通过考虑渐变来简化代码:

.positioned {
  position: relative;
  height: 15px;
  background:
   linear-gradient(red,red) left/80% 100% no-repeat,
   aquamarine;
  margin-bottom: 10px;
}
<div class="positioned"></div>