如何向背景图像添加颜色叠加层?

How to add a color overlay to a background image?

我在 SO 和 Web 上看到了很多这个问题。但其中 none 正是我要找的。

如何仅使用 CSS 将颜色叠加层添加到背景图像?

示例HTML:

<div class="testclass">
</div>

示例CSS:

.testclass {
    background-image: url("../img/img.jpg");
}

请注意:

这可能吗? (如果没有,我会感到惊讶,但我还没有找到任何相关信息),如果是的话,最好的方法是什么?

感谢所有建议!

background-image 取多个值。

所以只需组合一种颜色线性渐变和 css blend modes 就可以了。

.testclass {
    background-image: url("../images/image.jpg"), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5));
    background-blend-mode: overlay;
}

请注意,IE/Edge 根本不支持 CSS 混合模式。

您可以使用伪元素创建叠加层。

.testclass {
  background-image: url("../img/img.jpg");
  position: relative;
}
.testclass:before {
  content: "";
  position: absolute;
  left: 0; right: 0;
  top: 0; bottom: 0;
  background: rgba(0,0,0,.5);
}

我看到 2 个简单的选项:

  • 图像上具有半透明单一渐变的多重背景
  • 巨大的嵌入阴影

渐变选项:

html {
  min-height:100%;
  background:linear-gradient(0deg, rgba(255, 0, 150, 0.3), rgba(255, 0, 150, 0.3)), url(http://lorempixel.com/800/600/nature/2);
  background-size:cover;
}

影子选项:

html {
  min-height:100%;
  background:url(http://lorempixel.com/800/600/nature/2);
  background-size:cover;
  box-shadow:inset 0 0 0 2000px rgba(255, 0, 150, 0.3);
}

我的旧 codepen 例子很少


第三个选项

  • with background-blen-mode :

    The background-blend-mode CSS property sets how an element's background images should blend with each other and with the element's background color.

html {
  min-height:100%;
  background:url(http://lorempixel.com/800/600/nature/2) rgba(255, 0, 150, 0.3);
  background-size:cover;
  background-blend-mode: multiply;
}

试试这个,简单明了。我是从这里找到的:https://css-tricks.com/tinted-images-multiple-backgrounds/

.tinted-image {

  width: 300px;
  height: 200px;

  background: 
    /* top, transparent red */ 
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* bottom, image */
    url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}