CSS 背景渐变,图片

CSS background gradient, image

我的背景有问题:

  1. 我有 3 个子元素。
  2. 他们每个人都通过 #nth_image ID 获得了背景图像。
  3. 他们还通过 .background-gradient class.
  4. 获得了背景渐变
  5. 所有 png 图像都有 alpha 通道

问题是背景图像覆盖了背景渐变。

.background_gradient {
  background: -webkit-radial-gradient(top, ellipse cover, #f9f9f9 0%,#eaeaea 100%);
}
#first_image {
  background: url(images/img01.png);
}
#second_image {
  background: url(images/img02.png);
}
#third_image {
  background: url(images/img03.png);
}
<div class="parent">
  <div id="first_iamge" class="background_gradient"></div>
  <div id="second_image" class="background_gradient"></div>
  <div id="third_image" class="background_gradient"></div>
</div>

渐变和图像背景都使用相同的背景图像 属性。就好像你是这样写的:

.class {
  background-image: url('/path/to/image.png');
  background-image: -webkit-radial-gradient(top, ellipse cover, #f9f9f9 0%,#eaeaea 100%);
}

所以基本上你是用渐变覆盖背景的图像部分,反之亦然,这取决于哪个规则优先于另一个。

我的建议是以不同的方式设置标记的样式。在 div 里面有一个 div 和你想要的背景。

<div class="background-gradient">
  <div id="first-background"></div>
</div>

如果你想在单个元素上混合两种类型的背景,我的建议是使用 css 伪元素。 您可以使用与渐变部分元素大小相同的 before 伪元素。

你可以有这样的东西:

.background_gradient {
  position: relative;
}    
.background_gradient:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index:-1;
  background: -webkit-radial-gradient(top, ellipse cover, #f9f9f9 0%,#eaeaea 100%);
}
#first_image {
  background: url(images/img01.png);
}
#second_image {
  background: url(images/img02.png);
}
#third_image {
  position: relative;
  background: url(images/img03.png);
}