Reputation: 5670
I am trying to assign a background-image
and a background-color
to a div. There are many SO answers (like this) with the solution to either combine them in background
:
background: rgba(255,0,0,0.5) url('http://placehold.it/100x100');
Or use separate properties:
background-color: rgba(255,0,0,0.5);
background-image: url('http://placehold.it/100x100');
Neither of the above are working for me (tested in Firefox and Chrome) - I breifly see the correct background color and then it disappears and all that is left is the image. What does work for some reason is:
background: linear-gradient(to bottom, rgba(255,0,0,0.5) 0%, rgba(255,0,0,0.5) 100%), url('http://placehold.it/100x100');
Any idea why these solutions are not working?
UPDATE To better clarify what I am looking for: The color of the div is constantly changing, so I need to be able to dynamically and easily update an inline style with javascript. I was hoping there was a simple solution (as there was in 2011) using the standard background properties. If not, I'll set a linear gradient. It is a bit clunky, but it seems to work fine.
UPDATE2 In the end, I discovered that setting a gradient to the background-image was 3 times slower than setting a background-color property. Because this was part of a color picker, it created an unacceptable lag with mouse movement. I ended up using nested divs and keeping the image constant in the outer div and changing the color in the inner div.
Here is a demo:
#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>
Upvotes: 3
Views: 17064
Reputation: 883
You may use,
#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);
}
Upvotes: 1
Reputation: 3426
try this code
.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>
Upvotes: 2