Search code examples
htmlcsstagstransparency

How to add transparency to a background image? (HTML + CSS)


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.


Solution

  • 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')
    }