CSS background-image-opacity?

Viewed 373170

Related to How do I give text or an image a transparent background using CSS?, but slightly different.

I'd like to know if it's possible to change the alpha value of a background image, rather than just the colour. Obviously I can just save the image with different alpha values, but I'd like to be able to adjust the alpha dynamically.

So far the best I've got is:

<div style="position: relative;">
    <div style="position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px;
                      background-image: url(...); opacity: 0.5;"></div>
    <div style="position: relative; z-index: 1;">
        <!-- Rest of content here -->
    </div>
</div>

It works, but it's bulky and ugly, and messes things up in more complicated layouts.

13 Answers

Try this

<div style="background: linear-gradient( rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7) ), url(/image.png);background-repeat: no-repeat;  background-position: center;"> </div>

To set the opacity of a background image, you just need to add an opaque image as first image in the background-image set.

Explanation:

  • The gradient function is creating an image from a color
  • The rgba function is creating a color that accepts opacity as parameter (ie alpha parameters)
  • alpha = 1 - opacity of white
  • Therefore by combining them, you can create an opaque image.

For instance, you can add an opacity of 0.3 by adding the following image linear-gradient(to right, rgba(255,255,255, 0.7) 0 100%) in the set of background-image

Example for an opacity of 0.3

body{
  background-image: linear-gradient(to right, rgba(255,255,255, 0.7) 0 100%), url(https://images.unsplash.com/photo-1497294815431-9365093b7331?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80);
  background-size: cover;
}

Enjoy !

Credits

I use it, I tested it on a white background, but it can be matched to the background color, especially if using css var:

background: #ececec99;
background-blend-mode: lighten;
background-image: url(images/background-1.jpg);
background-repeat: no-repeat;
background-size: cover;
background-position: center;

It's important to note that I only checked this in the Chrome browser.

You can use a hack to achieve a filter effect. some users mentioned before but none of their answers worked for me except this solution

#item_with_background {
    background: rgb(filter_color) url(...)
}

#item_with_background > * {
    position: relative;
    z-index: 1; // this may cause other problems if you have other elements with higher than 1 z-index. so use with caution.
}

#item_with_background::before {
    content: ' ';
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(filter_color, 0.9);
    width: 100%;
    height: 100%;
    z-index: 0;
}

Here is a working example

Related