【问题标题】:CSS - before pseudo element behind element text [duplicate]CSS - 在元素文本后面的伪元素之前[重复]
【发布时间】:2021-06-21 09:59:30
【问题描述】:

我尝试学习如何在 CSS 中使用伪元素,但遇到了一个问题。我尝试创建一个包含一些文本和伪元素的容器。

但我不希望伪元素位于元素文本之后,而是在背景颜色之前。我不知道如何实现这一点。 我希望伪元素成为背景颜色的一部分和之前。但要在容器的实际内容后面。

这是我所面临的确切问题的简短 sn-p:

.container {
  height: 10rem;
  background-color: blue;
  color: white;
}

.container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 3rem;
  height: 3rem;
  background-color: red;
}
<div class="container">
  <h1>This is a title</h1>
</div>

【问题讨论】:

  • 如果::before 元素落后于蓝色.container 而不仅仅是文字,是否可以接受?
  • @Omkar76 不,这是不可接受的。我希望伪元素成为背景颜色的一部分和之前。但要在容器的实际内容后面。
  • 您所需要的只是位置:相对于 h1。不需要 z-index
  • @TemaniAfif 是的,但我希望能够在不同的页面中重用这个类。我希望它独立于它可能有也可能没有的子元素。
  • 但您接受了为子元素添加样式的答案。我给你一个简化的解决方案

标签: css positioning pseudo-element


【解决方案1】:

只需将z-index 设置为容器的子级即可。

.container {
  height: 10rem;
  background-color: blue;
  color: white;
}

.container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 3rem;
  height: 3rem;
  background-color: red;
}

.container>* {
  position: relative;
  z-index: 2;
}
<div class="container">
  <h1>This is a title</h1>
</div>

【讨论】:

  • 有没有办法在不使用额外的dom元素的情况下实现这一点?
  • @Stephen 已编辑。检查更新
猜你喜欢
  • 2019-06-02
  • 1970-01-01
  • 2011-09-26
  • 1970-01-01
  • 2014-10-31
  • 2016-08-14
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多