2

i'm trying to use opacity on a background-image but if i use it it will effect the text aswell.

.content_wrapper{
width:320px;
height:374px;
color:black;
background-image: url('../images/beuningse-boys-midden.png');
background-size:130px;
background-repeat: no-repeat;
background-position-x: 95px;
background-position-y: 155px;

}
  • 2
    Example - `background-color: rgba(0,0,0,0.5);` – Vucko Sep 29 '14 at 07:59
  • 1
    May you can follow this link for the answer :- http://stackoverflow.com/questions/7241341/can-i-set-an-opacity-only-to-the-background-image-of-a-div – Puneet Sep 29 '14 at 08:02
  • That is a good question, I have thought it too much time. But I haven't a appropriate answer. I use two `div` to achieve it. One contains content text, the other contains background image. – Todd Mark Sep 29 '14 at 08:03
  • Used to this http://jsfiddle.net/xb2bk7bp/ – Rohit Azad Malik Sep 29 '14 at 08:06

2 Answers2

1

You cannot change the opacity of a background-image with CSS. However, there are ways of achieving the same result.

Method 1

This method uses the :after pseudo class which is absolutely positioned inside its parent. The background image is set on this pseudo element along with the opacity giving the impression that the background opacity is set on the background itself.

HTML

<div>
  Text on top, no big deal, no big deal. Just a little text and stuff. That's all.
</div>

CSS

div {
  width:320px;
  height:374px;
  display: block;
  position: relative;
  border: solid 1px #f00;
}

div::after {
  content: "";
  background-image: url('http://placehold.it/800x600');
  background-size: cover;
  background-repeat: no-repeat;
  opacity: 0.5;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: -1;   
}


Method 2

If you need backwards compatibility, you will need an extra element in your markup to achieve the same result:

HTML

<div class="container">
    <div class="background"></div>
    Text on top, no big deal, no big deal. Just a little text and stuff. That's all.
</div>

CSS

.container {
  width:320px;
  height:374px;
  display: block;
  position: relative;
  border: solid 1px #f00;
}

.container .background {
  content: "";
  background-image: url('http://placehold.it/800x600');
  background-size: cover;
  background-repeat: no-repeat;
  opacity: 0.5;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  z-index: -1;   
}

Here is a great article with a CSS3 method of achieving the same result:

http://css-tricks.com/snippets/css/transparent-background-images/

Chris Spittles
  • 15,023
  • 10
  • 61
  • 85
0

Give to the text a class or an id and give it a color without opacity.

p {
    color: rgb(120,120,120); // use here what color you want
}
Florin Pop
  • 5,105
  • 3
  • 25
  • 58