我想将 ::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>
最佳答案
首先,这与百分比值无关。即使使用像素值并且宽度和高度都不起作用,您也会得到相同的结果。
伪元素是内联元素,它们的宽/高仅由它们的内容定义,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 的规则。为了计算宽度和高度。您还会注意到该元素将在显示中具有 block
的计算值。
你还应该注意 positioned element 的使用,这意味着 relative,absolute,fixed 或 sticky 但是使元素 position:relative
将保持内联level 元素,你仍然不能使用宽度/高度。
.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>
关于html - 为什么宽度/高度不适用于非定位伪元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53573836/