Kev Wilson Kev Wilson - 5 months ago 8
HTML Question

Can we still use background-image and background-color together?

I'm expecting this to be a silly mistake on my part, but I'm tearing my hair out with this one.

I cannot manage to set a background image and overlay a color to a div. I have the following CSS class:

.blue-pattern {
background-color: #4099FF;
background-image: url('/wp-content/themes/bones/library/images/backgrounds/pattern-bw.jpg');
background-position: top left;
background-repeat: repeat repeat;
}


Which is being added to a
div
like this

<div class="blue-pattern pad--tiny">
<p class="text--white">Blah blah blah, text and stuff</p>
</div>


But the color is not showing through. If I hide the
background-image
in dev tools then I see a solid blue background. But I can't get it to show over the
background-image

Answer

By default the background color is behind the background image, so if you specify one background, with a color and an image, the color will be invisible behind the image.

However, you can specify multiple backgrounds, each with their own properties. So one background can have an image, while another can have a color. And then the colored background can be over the image..

This is explained in detail in https://css-tricks.com/tinted-images-multiple-backgrounds/

The trick is to specify a semi-transparent colored background, and a separate image background. You can specify them comma separated. In the code below, the first background is semi-transparent background. A normal rgba() color cannot be used as a background, but you can fake it by defining a linear gradient with two times the same color. The color values are the decimal RGB values for your color, and the fourth parameter specified an opacity of 50%. The second background is the image itself.

.blue-pattern {
  background: 
    linear-gradient(
      rgba(64, 153, 255, 0.5), 
      rgba(64, 153, 255, 0.5)
    )    
    , url('/your image url');

In a full code sample it would look like this. Note that I've changes the url and skipped the other image properties.

.blue-pattern {
  background: 
    linear-gradient(
      rgba(64, 153, 255, 0.5), 
      rgba(64, 153, 255, 0.5)
    )    
    ,
   url('https://upload.wikimedia.org/wikipedia/commons/thumb/a/a8/Portrait_of_Arthur_Conan_Doyle.jpg/460px-Portrait_of_Arthur_Conan_Doyle.jpg');
    
}

.pad--tiny {
  height: 500px; /* for demo */ 
}
<div class="blue-pattern pad--tiny">
    <p class="text--white">Blah blah blah, text and stuff</p>                                   
</div>

Note that multiple backgrounds are not supported in IE8 and the gradient isn't well supported in IE9, so you may want to take that into account.