首页 > 解决方案 > 在 CSS 中设置伪元素尺寸

问题描述

我目前正在尝试设置 :before 伪元素宽度,以匹配元素本身的尺寸(在本例中为锚标记),目的是创建覆盖整个元素的叠加层。为了演示,对于这个示例,我将考虑使用 Google 的网页进行演示:

a.gb_g::before {
    background-color: rgba(255, 0, 0, 0.2);
    position: absolute;
    content: 'hello';
    display: block;
    position: absolute;
}
<div class="gb_h gb_i">
      <a class="gb_g" data-pid="23" href="https://mail.google.com/mail/?tab=wm&amp;ogbl">Gmail</a>
</div>

但是,这会产生以下结果:

来自 Google 网页的 Gmail 和图片链接 - 显示尺寸不正确的叠加层

我也尝试过设置width: 100%,但这会导致容器溢出。是否可以设置伪元素宽度,以完美匹配元素本身的宽度(在本例中为“Gmail”/“图像”链接)?期望的结果是覆盖完全覆盖每个锚标记,而不对元素本身进行任何 CSS 更改。

基本上,我面临的情况是我有一个固定的网页布局(现有样式我无法控制),为此我想突出显示网页的某些部分(包括一些链接)。因此,理想情况下,任何提议的解决方案都将对现有页面布局造成最小的影响,这就是我尝试选择完全基于伪元素的解决方案的原因。

标签: htmlcsspseudo-element

解决方案


这对你有用吗?添加 position: relative to the element 和 width: 100% 到伪元素为我解决了这个问题。

a.gb_g::before {
    background-color: rgba(255, 0, 0, 0.2);
    position: absolute;
    content: 'hello';
    display: block;
    position: absolute;
    width: 100%;
}

a.gb_g{
    position: relative;
}
<div class="gb_h gb_i">
      <a class="gb_g" data-pid="23" href="https://mail.google.com/mail/?tab=wm&amp;ogbl">Gmail</a>
</div>


推荐阅读