在渐变叠加层上使用背景剪辑

Using background-clip on a gradient overlay

我想要达到的目标:

两个元素(箭头容器 + 全宽条)共享相同的渐变。我试过的是分别制作两个元素,然后将渐变应用于它们,但由于显而易见的原因,它看起来被剪裁了:

Codepen: https://codepen.io/sigurdmazanti/pen/bGarpvJ

片段:

.container {
  background: white;
  width: 100%;
  height: 71px;
}

.arrow-container {
  height: 34px;
  width: 118px;
  border-radius: 15px 15px 0 0;
  text-align: center;
  margin: 0 auto;
  color: white;
  background: transparent linear-gradient(180deg, #415fb4 0%, #0e2460 100%) 0 0 no-repeat padding-box;
}

.bar {
  height: 37px;
  background: transparent linear-gradient(180deg, #415fb4 0%, #0e2460 100%) 0 0 no-repeat padding-box;
}
<div class="container">
  <div class="arrow-container">&#x2191;</div>
  <div class="bar"></div>
</div>

然后我想到了使用渐变的全宽+全高叠加,然后使用background-clip来裁剪这两个元素,所以它们都共享渐变。但是我有点吃力,似乎我用错了方法。

Codepen: https://codepen.io/sigurdmazanti/pen/popryWz

片段:

.container {
  overflow: hidden;
  background: white;
  width: 100%;
  height: 71px;
}

.bg-gradient {
  background: transparent linear-gradient(180deg, #415fb4 0%, #0e2460 100%) 0 0 no-repeat padding-box;
  background-clip: content-box;
  width: 100%;
  height: 100%;
}

.arrow-container {
  height: 34px;
  width: 118px;
  border-radius: 15px 15px 0 0;
  text-align: center;
  margin: 0 auto;
  background-color: red;
}

.bar {
  height: 37px;
  background-color: red;
}
<div class="container">
  <div class="bg-gradient">
      <div class="arrow-container">&#x2191;</div>
      <div class="bar"></div>
  </div>
</div>

我不能使用 ::after::before 伪元素,它们需要是两个独立的元素,因为箭头元素需要一个事件处理程序。 我走在正确的道路上吗,或者这是可以实现的吗?

谢谢!

使渐变的高度等于两个元素的总和然后控制大小:

.container {
  background: white;
  height: 71px;
}

.arrow-container {
  height: 34px;
  width: 118px;
  border-radius: 15px 15px 0 0;
  text-align: center;
  margin: 0 auto;
  color: white;
  background: 
  linear-gradient(180deg, #415fb4 0%, #0e2460 100%) top/100% 71px;
}

.bar {
  height: 37px;
  background: 
  linear-gradient(180deg, #415fb4 0%, #0e2460 100%) bottom/100% 71px;
}
<div class="container">
  <div class="arrow-container">&#x2191;</div>
  <div class="bar"></div>
</div>

或者像下面这样使用伪元素:

.container {
  background: white;
  height: 71px;
  position:relative; /* relative here */
  z-index: 0;
}

.arrow-container {
  height: 34px;
  width: 118px;
  border-radius: 15px 15px 0 0;
  text-align: center;
  margin: 0 auto;
  color: white;
}

.bar {
  height: 37px;
}

.arrow-container,
.bar {
 -webkit-mask:linear-gradient(#000 0 0); /* clip the gradient to the element area */
}

/* your gradient here */
.arrow-container:before,
.bar:before {
  content:"";
  position:absolute;
  inset:0;
  background: linear-gradient(180deg, #415fb4 0%, #0e2460 100%);
  z-index:-1;
}
<div class="container">
  <div class="arrow-container">&#x2191;</div>
  <div class="bar"></div>
</div>