首页 > 解决方案 > 堆叠时边框中的自定义渐变不起作用

问题描述

我有这个例子,我试图用 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>

标签: htmlcssz-index

解决方案


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

因此,container具有z-indexauto高于 z-index.card:after。这就是为什么它在black后台。


你可以这样做:

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

Codepen上进行检查。


推荐阅读