0

I have gone through weird problem (for me as a beginner in CSS world). I was trying to have a background-image with a transparent color on top of it. Image was the main page background:

body {

font-family: 'Raleway', 'Open Sans', sans-serif;
font-weight: 400;
line-height: 1.6;
background: rgba(0,0,0,.3) url('..img/image.jpg') no-repeat;
background-size: cover;

min-height: 100vh; }

This didn't work for me. Don't know why?

I checked the dev tools, I added separate background-color and it didn't work as well. I tried to find solution here: Semi-transparent color layer over background-image? and treid proposed solutions. Didn't work for me.

But when I added class to the and created this lines:

.body {
background: 
    linear-gradient(
    rgba(0, 0, 0,.5), 
    rgba(0, 0, 0,.5)
),
    url('../img/bg_image.jpg') no-repeat;
background-size: cover; }

It worked! But I still don't know why?

Is it the specificity problem? Perhaps something different? If there is someone who can ansewer my question (with qucik example) I will be grateful.

So the solution I found myslef is the code above but I don't understand whe previous attempt didn't worked form me.

Cheers, Kamil

Kami
  • 1
  • 1
  • 1
  • 2

2 Answers2

7

As stated in the documenation:

You can apply multiple backgrounds to elements. These are layered atop one another with the first background you provide on top and the last background listed in the back. Only the last background can include a background color.

And if we check the background property:

enter image description here

So this is not valid as background:

body {
  background:rgba(255,0,0,0.5) ,url(https://lorempixel.com/400/200/);
}

But this is valid:

body {
  background: linear-gradient(rgba(255,0,0,0.5),rgba(255,0,0,0.5)),url(https://lorempixel.com/400/200/);
}
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
0

The css background property is actually a shorthand for various properties, as it is explained here. One of those properties is the background-image, this property supports images and gradients, but the important part is that it also supports Multiple Background Images, with this in mind you can add as many backgrounds as you like to the same element.

background: url(test.pnd), linear-gradient(...),...

In your first example you are using a

rgba(0, 0, 0,.5), 

This is not a linear-gradient, neither an image is a background-color property, that is why it won't work.

A nice example for this use is the background [patterns created by Lea Verou.]

The stacking order of multiple backgrounds, is by default the first is on top and they go down from there. 4

Renzo Calla
  • 7,486
  • 2
  • 22
  • 37