如何定义 :before 伪元素相对于包含元素的宽度

How to define width of :before pseudo element relative to containing element

我想在特定的词上放置一个图像圈。

<p>
   <span class="Subjekt">Vater</span>
   <span class="Praedikat">bringt</span>
</p>

.Subjekt:before {
    position: absolute;
    background-image: url(images/markup/einkreisen1.png);
    background-size: 100% 100%;
    display: inline-block;
    margin-left: -20px;
    width: 100px; 
    height: 50px;
    content:"";
}

效果很好。但尺寸固定。

有没有办法定义伪元素相对于 .Subjekt 元素的宽度?

相对于 Subjekt 元素对 before 元素使用 relative 定位。

参见下面的示例:

  1. relative 位置Subjekt

  2. 尝试改变 Subjektwidthheight(请注意,我已将元素设置为 inline-block,因为 inline 元素- 这是默认显示类型- 不会占用宽度或高度)

  3. before元素的heightwidth设为100%。

  4. 后面before的地方我给了z-index: -1

.Subjekt {
    position: relative;
    width: 200px;
    height: 200px;
    display: inline-block;
}
.Subjekt:before {
    position: absolute;
    background-image: url(http://placehold.it/100x100);
    background-size: 100% 100%;
    display: inline-block;
    width: 100%; 
    height: 100%;
    content:"";
    z-index: -1;
}
<p>
   <span class="Subjekt">Vater</span>
   <span class="Praedikat">bringt</span>
</p>

希望你能从这里开始。让我知道您对此的反馈。谢谢!