0

I have a DIV with some

text and a background image. I want to reduce the opacity of the background image. But when I apply opacity to the DIV it affects the texts within the DIV. How do I change the opacity of the background image without changing the opacity of the texts in the DIV?

I have this code I got from another question on stackoverflow, which I use to reduce opacity of another div but i dont know how to modify it to achieve the above question.

function convertHex(hex,opacity){
hex = hex.replace('#','');
r = parseInt(hex.substring(0,2), 16);
g = parseInt(hex.substring(2,4), 16);
b = parseInt(hex.substring(4,6), 16);

result = 'rgba('+r+','+g+','+b+','+opacity/100+')';
return result;
}


$(".add_to_cart_button").click(function() {

$(".cart-contents").css("background-color",convertHex('#f47d32',40));
});
Joseph
  • 313
  • 1
  • 4
  • 16
  • 1
    This topic is covered here: http://stackoverflow.com/questions/4183948/css-set-background-image-with-opacity – Vladimir M Sep 20 '16 at 20:28
  • Is that picture dynamic or static? If static you can reduce it's opacity at Photoshop or similiar software, and then save it as .PNG. Note, this is just one of the options. – harisdev Sep 20 '16 at 20:31
  • Also relevant: [Set opacity of background image without affecting child elements](http://stackoverflow.com/questions/4997493/set-opacity-of-background-image-without-affecting-child-elements) – showdev Sep 20 '16 at 20:49

2 Answers2

1

First step is add z-index: -1; and position: relative; to your back div css:

Ways to change opacity background:

$("#backDiv").css("opacity", "0.4");
$("#backDiv").css({ opacity: 0.4 });
$("#backDiv").fadeTo("slow", 0.4);
$("#backDiv").fadeTo(1000, 0.4); // fist parameter is animate time in ms

Test button with possibility do some action after the animation:

$("#buttonTest").click(function() {
  $("#backDiv").fadeTo("slow" , 0.4, function() {
    // Animation complete. You can add some action.
  });
});

I hope it helps...

Good Luck!

ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58
0

I think below is something you are looking for:

#d1 {
  background: url("http://666a658c624a3c03a6b2-25cda059d975d2f318c03e90bcf17c40.r92.cf1.rackcdn.com/unsplash_527bf56961712_1.JPG");
  height: 200px;
  width: 500px;
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(255, 255, 255, 0.7);
  height: 100%;
  width: 100%;
  display: block;
}

#d2 {
  color: red;
  position: relative;
}
<div id="d1">
  <div class="overlay"> </div>
  <div id="d2">
    Test content
  </div>
</div>
Nimmi
  • 1,997
  • 2
  • 12
  • 20