1

I have these lines In my CSS file:

body {
    background: url(https://images.freeimages.com/images/large-previews/48d/woodgrain-texture-1151631.jpg);
}

How can I affect this image with transparency? I found a "solution" that looked like this:

img {
    opacity: 0.5
}

But I don't really know how to apply It. If I just write It down, nothing happens because I don't know how to connect It to the image I want to use.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Lusks
  • 31
  • 6
  • The `img` rule would apply to an `img` tag. You've got your image as a background, so you might need something like https://stackoverflow.com/questions/12605908/change-background-image-opacity – jmargolisvt May 26 '20 at 23:43

2 Answers2

2

You would simply apply it as shown below;

body:before { 
  content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1;
    background-image: url('https://miro.medium.com/max/1400/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg');
   opacity: 0.5;
}

.content {
    position: relative; 
    z-index: 2;
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
  </head>

  <body>
    <h1 class="content">Hey!</h1>
  </body>
</html>

The body being your background and the content being your text and other content etc..

UnReal G
  • 106
  • 2
  • 8
2

You can utilize the rgba() function of the background property and combine it with the url() function. The RGBA has the A for "Alpha" in addition to Red-Green-Blue, which performs just like the opacity property; values range from 0 to 1. The trick to using RGBA in a background image is to use two parallel rgba() functions inside a linear-gradient(). Since rgba() returns a color value, it can be utilized as two color stops in the linear gradient...although they technically aren't color stops, since no transition happens from two like color values. Hackish, but simple and functional.

body { 
    background: linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)), 
                url('https://images.freeimages.com/images/large-previews/48d/woodgrain-texture-1151631.jpg')
}
Max Voisard
  • 1,685
  • 1
  • 8
  • 18