html - 为什么宽度/高度不适用于非定位伪元素?

标签 html css css-position

我想将 ::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 的计算值。

enter image description here

你还应该注意 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/

相关文章:

html - 显示嵌套的 div 失败

html - 在顶部水平对齐 div 内的元素

css - 固定位置在 Chrome 上不起作用

html - 如何使具有相对位置的 div 居中,这也是 css 中的显示表格单元格?

javascript - 如何在html上停止自动样式

javascript - 在 mozilla/IE 中淡出无法正常工作

html - 在我的例子中如何将垂直对齐设置为中间?

css-only 100% div height with dynamic height footer

html - 高度可变的固定元素下方的静态元素

javascript - 检查 gridview 第一列中的所有复选框?