CSS: 背景图片不透明的背景颜色

CSS: background color with opacity on background image

我正在尝试将 background-imagebackground-color 分配给 div。有许多 SO 答案 (like this) 以及将它们组合成 background:

的解决方案
background: rgba(255,0,0,0.5) url('http://placehold.it/100x100');

或使用单独的属性:

background-color: rgba(255,0,0,0.5);
background-image: url('http://placehold.it/100x100');

以上都不适合我(在 Firefox 和 Chrome 中测试)- 我短暂地看到了正确的背景颜色,然后它消失了,剩下的就是图像。由于某种原因起作用的是:

 background: linear-gradient(to bottom, rgba(255,0,0,0.5) 0%, rgba(255,0,0,0.5) 100%), url('http://placehold.it/100x100');

知道为什么这些解决方案不起作用吗?

UPDATE 为了更好地阐明我在寻找什么: div 的颜色在不断变化,所以我需要能够动态且轻松地更新一个javascript 的内联样式。我希望有一个使用标准背景属性的简单解决方案(就像 2011 年那样)。如果没有,我会设置一个线性渐变。它有点笨重,但似乎工作正常。

UPDATE2 最后,我发现为背景图像设置渐变比设置背景颜色慢 3 倍 属性。因为这是颜色选择器的一部分,所以它会导致鼠标移动出现不可接受的延迟。我最终使用了嵌套 divs 并在外部 div 中保持图像不变并更改内部 div.

中的颜色

这是一个演示:

#div1 {
  height: 100px;
  width: 100px;
  background-color: rgba(255,0,0,0.5);
  background-image: url('http://placehold.it/100x100');
}

#div2 {
  height: 100px;
  width: 100px;
  background: linear-gradient(to bottom, rgba(255,0,0,0.5) 0%, rgba(255,0,0,0.5) 100%), url('http://placehold.it/100x100');
}
<div id="div1">
</div>

<div id="div2">
</div>

你可以使用,

#div1 {
 width: 100px;
 height: 100px;
 background: url('http://placehold.it/100x100') center center no-repeat;
 background-size: cover;
 }

 #div1:before {
   content: '';
   position: absolute;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   background-color: rgba(255,0,0,0.5);
 }

试试这个代码

.background {
    background:url('http://placehold.it/100x100');
    position: relative;
    height: 100px;
  width: 100px;
}

.layer {
    background-color: rgba(75, 86, 160, 0.7);
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
<div class="background">
    <div class="layer">
    </div>
</div>