我想设置一个width of ::before伪元素达到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>
首先,这与百分比值无关。即使使用像素值并且宽度和高度都不起作用,您也会得到相同的结果。
伪元素是inline元素及其宽度/高度仅由其内容定义,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 https://developer.mozilla.org/en-US/docs/Web/CSS/::before
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 https://www.w3.org/TR/CSS2/visudet.html#the-width-property
The 'height' property does not apply. The height of the content area should be based on the font ... ref https://www.w3.org/TR/CSS2/visudet.html#inline-non-replaced
通过制作伪元素position:absolute
您现在将考虑适用于的规则绝对定位元素 https://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width以便计算宽度和高度。您还会注意到该元素的计算值为block
显示内。
您还应该注意使用定位元素这意味着相对、绝对、固定或粘性,但使元素position:relative
会将其保留为内联级别元素,但您仍然无法使用宽度/高度。
.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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)