结合CSS背景直线渐变

时间:2018-04-09 08:44:36

标签: css css3 background background-image linear-gradients

如何在两个单独的类css中组合这一行?

background: url('image1.png') center 50% no-repeat, url('image2.png') 100% 100% no-repeat, linear-gradient(#000000, #ffffff);

特别是我需要一个不同的线性渐变

的css类

像...一样的东西。

.a {
   background-image: url('image1.png');
   background-position: center 50%;
   background-repeat: no-repeat;
   background-image: url('image2.png');
   background-position: 100% 100%;
   background-repeat: no-repeat;
}

.b {
   background-image: linear-gradient(#000000, #ffffff);
}

<div class="a b"></div>

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以依赖CSS变量并执行以下操作:

&#13;
&#13;
:root {
 /* The default gradient is transparent */
 --c:linear-gradient(transparent,transparent)
}

.a,.c {
  height:150px;
  width:150px;
  display:inline-block;
  background-image:var(--c),url(https://lorempixel.com/400/200/);
  background-size:auto,cover;
}

.c {
  background-image:
  radial-gradient(circle at center,pink 20%,transparent 30%),
  var(--c),
  url(https://lorempixel.com/400/400/);
}
.b {
 --c:linear-gradient(red,transparent)
}
.d {
 --c:linear-gradient(to right,blue,transparent)
}
&#13;
<div class="a">
</div>

<div class="a b">
</div>

<div class="c d">
</div>

<div class="a d">
</div>
&#13;
&#13;
&#13;

<强>更新

另一个想法是使用旧的伪元素技巧但这只有在渐变应位于顶层或底层时才有效:

&#13;
&#13;
.a,.c {
  height:150px;
  width:150px;
  display:inline-block;
  background-image:url(https://lorempixel.com/400/200/);
  background-size:cover;
}

.c {
  background-image:url(https://lorempixel.com/400/400/);
}
.b,.d {
  position:relative;
  z-index:0;
}
.b:before,.d:before {
  content:"";
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  z-index:1;
  background:linear-gradient(red,transparent);
}
.d:before {
 background:linear-gradient(to right,blue,transparent);
}
&#13;
<div class="a">
</div>

<div class="a b">
</div>

<div class="c d">
</div>

<div class="a d">
</div>
&#13;
&#13;
&#13;