有没有办法在文本节点后面放置一个伪元素?

时间:2021-04-26 09:43:09

标签: html css

我有一个以 ::before 伪元素作为背景的元素。

但是正如你所看到的,伪元素覆盖了我的文本。

.wrapper {
  background-color: salmon;
  padding: 20px;
}

.tag {
  position: relative;
  display: inline-block;
}

.tag::before {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transform: scaleX(1.2) translateY(50%);
  background-image: radial-gradient(closest-side, steelblue 99%, transparent 100%);
}
<div class="wrapper">
  <span class="tag">Lorum ipsum</span>
</div>

我希望我可以通过

定位文本节点
.tag:text {
  z-index: 1;
}

但这是不可能的。

我试图给伪元素 z-index: -1; 但它被任何具有背景的东西覆盖,例如 .wrapper,因为它们所有的背景都有 z-index 的默认 0

.wrapper {
  background-color: salmon;
  padding: 20px;
}

.tag {
  position: relative;
  display: inline-block;
}

.tag::before {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transform: scaleX(1.2) translateY(50%);
  background-image: radial-gradient(closest-side, steelblue 99%, transparent 100%);
  z-index: -1;
}
<div class="wrapper">
  <span class="tag">Lorum ipsum</span>
</div>

我想要达到的目标:

enter image description here

如何在不修改html结构的情况下实现?

2 个答案:

答案 0 :(得分:2)

z-index上添加.tag

.tag {
      position: relative;
      display: inline-block;
      z-index: 1;
    }

.wrapper {
  background-color: salmon;
  padding: 20px;
}

.tag {
  position: relative;
  display: inline-block;
  z-index: 1;
}

.tag::before {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transform: scaleX(1.2) translateY(50%);
  background-image: radial-gradient(closest-side, steelblue 99%, transparent 100%);
  z-index: -1;
}
<div class="wrapper">
  <span class="tag">Lorum ipsum</span>
</div>

答案 1 :(得分:0)

z-index 上的正值 .tag.tag::before 上的负值

.wrapper {
  background-color: salmon;
  padding: 20px;
}

.tag {
  position: relative;
  display: inline-block;
  z-index: 1;
}

.tag::before {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transform: scaleX(1.2) translateY(50%);
  background-image: radial-gradient(closest-side, steelblue 99%, transparent 100%);
  z-index: -1;
}
<div class="wrapper">
  <span class="tag">Lorum ipsum</span>
</div>

相关问题