【问题标题】:z-index not working properly with pseudo-element [duplicate]z-index 无法与伪元素一起正常工作 [重复]
【发布时间】:2021-05-22 18:43:59
【问题描述】:

我试图在锚点/按钮周围制作边框,但不知何故 z-index 在以下代码中不起作用,即使我为它们中的任何一个分配了位置。 它在一定程度上与负 z-index 一起工作(但其他伪类,如 :hover 等将不起作用 -> 请参阅我的最后一个问题),但有人可以解释为什么 ::before 伪元素一直显示在按钮上方而不是下方?

这是我的代码:

.start-coding {
  display: block;
  font-size: 1.3rem;
  color: white;
  background-color: black;
  padding: 0.4rem 1.8rem;
  position: relative;
  z-index: 5;
  border-radius: 5px;
  width: 100%;
}

.start-coding::before {
  content: '';
  background: linear-gradient(115deg, #4fcf70, #fad648, #a767e5, #12bcfe, #44ce7b);
  border-radius: 5px;
  position: absolute;
  top: -3px;
  left: -3px;
  right: -3px;
  bottom: -3px;
  z-index: 1;
}
<a href="#" class="start-coding">Start Coding</a>

【问题讨论】:

  • 这个网站解释了原因:independent-software.com/… 顺便说一句,还有一件事,:hover 不适用于 ::after::before,因为实际上它们是虚构的元素。

标签: html css z-index pseudo-element


【解决方案1】:

那是因为您将伪元素绝对定位在 <a> 元素中,这导致它堆叠在具有静态定位的文本节点的顶部。

要解决这个问题,只需用<span> 包裹内部文本,然后添加此规则:

.start-coding > span {
  position: relative;
  z-index: 2;
}

更好的是:您甚至不需要将 z 索引添加到 ::before 和嵌套的 <span>,因为它们的顺序可以确保当它们被放置在堆叠上下文中时,@ 987654326@ 将始终位于顶部(因为它位于 DOM 树中的 ::before 元素之后)。见例子:

.start-coding {
  display: block;
  font-size: 1.3rem;
  color: white;
  background-color: black;
  padding: 0.4rem 1.8rem;
  position: relative;
  z-index: 5;
  border-radius: 5px;
  width: 100%;
}

.start-coding::before {
  content: '';
  background: linear-gradient(115deg, #4fcf70, #fad648, #a767e5, #12bcfe, #44ce7b);
  border-radius: 5px;
  position: absolute;
  top: -3px;
  left: -3px;
  right: -3px;
  bottom: -3px;
}

.start-coding>span {
  position: relative;
}
<a href="#" class="start-coding"><span>Start Coding</span></a>

【讨论】:

  • 非常感谢!欣赏!
猜你喜欢
  • 2022-01-23
  • 2012-01-08
  • 1970-01-01
  • 2011-12-10
  • 2020-07-02
  • 2017-09-29
  • 1970-01-01
  • 2012-01-31
  • 2019-11-30
相关资源
最近更新 更多