代码之家  ›  专栏  ›  技术社区  ›  Questionnaire

在CSS中设置伪元素维度

  •  -1
  • Questionnaire  · 技术社区  · 6 年前

    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>

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

    Gmail and Images links from Google's web page - showing overlays with incorrect dimensions

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

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

    2 回复  |  直到 6 年前
        1
  •  0
  •   Mahatmasamatman    6 年前

    这对你有用吗?添加位置:相对于元素,宽度: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>
        2
  •  0
  •   Mitth'raw'nuruodo    6 年前

    不确定这是否正是您想要的,但是您可以为实际元素添加“position:relative”,然后为::before添加“width:100%”。可以使用“overflow:hidden”和“white space:nowrap”来完全包含伪元素。

    a.gb_g {
        position: relative;
    }
    a.gb_g::before {
        background-color: rgba(255, 0, 0, 0.2);
        position: absolute;
        content: 'overlay text long';
        color: white;
        display: block;
        width: 100%;
        overflow: hidden;
        white-space: nowrap
    }
    <div class="gb_h gb_i">
      <a class="gb_g" data-pid="23">Original Text</a> Next
    </div>