0

How do I darken the background image without this affecting my text color?

http://jsfiddle.net/tx58qf3m/

div {
    display:block;
    background:url('http://placehold.it/500x500') 0 0 no-repeat;
    background-color:rgba(0, 0, 0, 1);
    background-size:cover;
    height:500px;
    width:500px
}
    
    
<div>
    
    <h1>Hello, it's me!</h1>
    
</div>
michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190
  • I think you will need to use a seperate element. You could, for example, use an `:before` pseudo element, z-index it to the back, give it full width and height, apply the background and opacity et voila. The only issue there is layering it correctly, in that case you _still_ need a seperate element to raise over your `:before` element – somethinghere Nov 26 '15 at 16:07
  • 5
    Check this link http://stackoverflow.com/questions/21957356/darken-a-background-image-without-affecting-the-text – Collins Abitekaniza Nov 26 '15 at 16:11
  • Flagged it as duplicate and posted my answer there. I leave it here as well just in case. – Szabolcs Páll Nov 26 '15 at 16:17

3 Answers3

1

Using :before

div {
    display:block;
    background:url('http://placehold.it/500x500') 0 0 no-repeat;
    background-color:rgba(0, 0, 0, 1);
    background-size:cover;
    height:500px;
    width:500px
}
  div:before {
  content: "";
  position: absolute;
  width: 100%; 
  height: 100%;  
  opacity: .4; 
  z-index: 1;
  background-color:black
}  

http://jsfiddle.net/tx58qf3m/14/

holden
  • 1,721
  • 12
  • 19
1

As you can see, change the opacity of the parent element will affect the child element, which is the h1 in your example.

You have a few different options to accomplish this without affect the child element.

1) Edit the opacity in an image editor (obvious and takes the least amount of code)

2) Use a pseudo element to contain your background image and make the opacity changes there - DEMO

3) Rather than applying your background-image to the div, make another child element to contain the image - DEMO

Don't forget to adjust your z-index values.

justinw
  • 3,856
  • 5
  • 26
  • 41
0

Like this

 <style>

 Div {
  Position:relative;
}

 Div:before {
  Content:'';
  Position:absolute;
  Top:0;
  Left:0;
  Background-color:rgba (0,0,0,.5);
  Width:100%;
  Height:100%;
  Z-index:2;
  }

 Div H2 {
 Position:relative;
 Z-index:3;
 }
  </style>
Naci
  • 5
  • 3