css 每当元素出现时,防止渐变背景继续进入整个页面

xe55xuns  于 2023-05-02  发布在  其他
关注(0)|答案(1)|浏览(108)

我有一个在Flex容器中重复的元素。该元素依次有3个元素。为了共享线性梯度,使用background-attachment:fixed,但这会导致梯度在元素之间继续。
这些元件进而具有被应用的一些绝对/相对定位。如果必须在Flex容器内重复此操作,则渐变将继续,这是不希望的。

.wrapper1 {
  height: 50px;
  position: relative;
  width: 30px;
  left: 80px;
}

.wrapper2 {
  height: 50px;
  position: absolute;
  width: 30px;
  left: -40px;
}

.wrapper3 {
  height: 50px;
  position: absolute;
  width: 30px;
  right: 90px;
}

.wrapper1,
.wrapper2,
.wrapper3 {
  background: linear-gradient(to right, red, blue);
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-origin: content-box;
}
<div style="display: flex; gap: 200px">
  <div class="wrapper1 component1">
    <div class="wrapper2"></div>
    <div class="wrapper3"></div>
  </div>

  <div class="wrapper1 component2">
    <div class="wrapper2"></div>
    <div class="wrapper3"></div>
  </div>
</div>

我基本上希望component1component2具有不连续的梯度,但component1component2必须具有不连续的梯度。Expecting similar outcome

bq3bfh9z

bq3bfh9z1#

我认为这是不可能做到这一点,因为设置 * 背景:* linear-gradient(to right, red, blue);,这意味着从左到右,它会改变颜色,它的100%,你不能削减它。您添加的background-attachment: fixed;在您的.wrapper类上创建了share color,但您不能在您的side div上重新开始。
如果你真的需要这样做,我建议手动(* 不推荐 *)。我只是做了这个,所以你可以参考它。

.wrapper{
  flex: 1;
  display: flex;
  gap: 200px;
}
.wrapper1 {
  height: 50px;
  position: relative;
  width: 30px;
  left: 80px;
}

.wrapper2 {
  height: 50px;
  position: absolute;
  width: 30px;
  left: -40px;
}

.wrapper3 {
  height: 50px;
  position: absolute;
  width: 30px;
  right: 90px;
}

.wrapper1.component1,
.component1 .wrapper2,
.component1 .wrapper3{
  background: linear-gradient(to right, red 1px, blue 200px);
  background-attachment: fixed;
  background-origin: content-box;
  
}

.wrapper1.component2,
.component2 .wrapper2,
.component2 .wrapper3{
  background: linear-gradient(to right, red 230px, blue 430px);
  background-attachment: fixed;
  background-origin: content-box;
  
}
<div class="wrapper">
  <div class="wrapper1 component1">
    <div class="wrapper2"></div>
    <div class="wrapper3"></div>
  </div>

  <div class="wrapper1 component2">
    <div class="wrapper2"></div>
    <div class="wrapper3"></div>
  </div>
</div>

相关问题