CSS Background Opacity [duplicate]

Children inherit opacity. It'd be weird and inconvenient if they didn't.

You can use a translucent PNG file for your background image, or use an RGBa (a for alpha) color for your background color.

Example, 50% faded black background:

<div style="background-color:rgba(0, 0, 0, 0.5);">
   <div>
      Text added.
   </div>
</div>

You can use pseudo-elements ::before or ::after to get a semi-transparent background and you can do this with just one container. Use something like this:

<article>
  Text.
</article>

Then apply some CSS:

article {
  position: relative;
  z-index: 1;
}

article::before {
  content: "";
  position: absolute;
  top: 0; 
  left: 0;
  width: 100%; 
  height: 100%;  
  opacity: .4; 
  z-index: -1;
  background: url(path/to/your/image);
}

Example:

body {
  background: red;
}

article {
  position: relative;
  z-index: 1;
}

article:before {
  content: " ";
  position: absolute;
  top: 0; 
  left: 0;
  width: 100%; 
  height: 100px;  
  opacity: .4; 
  z-index: -1;
  background: url(https://31.media.tumblr.com/8ec07e49f33088c2e32c158ca4262eb2/tumblr_n5wav6Tz4R1st5lhmo1_1280.jpg);
}
<article>
  Text.
</article>

Note: You might need to adjust the z-index values.


The following methods can be used to solve your problem:

  1. CSS alpha transparency method (doesn't work in Internet Explorer 8):

    #div{background-color:rgba(255,0,0,0.5);}
    
  2. Use a transparent PNG image according to your choice as background.

  3. Use the following CSS code snippet to create a cross-browser alpha-transparent background. Here is an example with #000000 @ 0.4% opacity

    .div {
        background:rgb(0,0,0);
        background: transparent\9;
        background:rgba(0,0,0,0.4);
        filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#66000000,endColorstr=#66000000);
        zoom: 1;
    }
    .div:nth-child(n) {
        filter: none;
    }
    

For more details regarding this technique, see this, which has an online CSS generator.


I would do something like this

<div class="container">
  <div class="text">
    <p>text yay!</p>
  </div>
</div>

CSS:

.container {
    position: relative;
}

.container::before {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: url('/path/to/image.png');
    opacity: .4;
    content: "";
    z-index: -1;
}

It should work. This is assuming you are required to have a semi-transparent image BTW, and not a color (which you should just use rgba for). Also assumed is that you can't just alter the opacity of the image beforehand in Photoshop.