堆叠时边框中的自定义渐变不起作用

Custom gradient in border is not working when stacked

我有这个例子,我试图在 CSS 中制作带有渐变的边框:https://codesandbox.io/s/sparkling-pine-uvdcj?file=/src/styles.css

如您所见,我可以在第一张卡片中显示边框,那张卡片没有堆叠到容器中(只是一个简单的 div 带背景)。

当我将相同的组件放入另一个元素(如容器)时,我根本无法显示边框。

有什么问题?

这里是 CSS 和 HTML:

body {
  background-color: gray;
}

.container {
  background-color: black;
  padding: 10px;
  margin: 10px;
}

.card {
  position: relative;
  margin-top: 32px;
  width: 300px;
  height: 180px;
  border-radius: 32px;
  background: linear-gradient(45deg, #1b1a1f, #1b1a1f 65%, rgba(77, 58, 40, 1));
  box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.2);
}

.card:after {
  content: "";
  position: absolute;
  display: block;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  height: 182px;
  width: 302px;
  border-radius: inherit;
  margin: -1px;
  background: linear-gradient(40deg, #1b1a1f, #1b1a1f 60%, #ffb966 90%);
  z-index: -1;
}
<div class="card"></div>
<div class="container">
  <div class="card"></div>
</div>

发生这种情况是因为您给出了 -1.card:after z-index。而默认 z-indexauto 或者您可以将其视为 0.

因此,container 具有 autoz-index,高于 .card:afterz-index。这就是为什么它在 black 背景后面。


您可以通过以下方式进行:

  • 将以下样式添加到 .container
.container {
  position: relative;
  z-index: -2;
}

Check it in action on Codepen.