Background image transparency with CSS3?

后端 未结 8 2173
生来不讨喜
生来不讨喜 2020-12-29 06:41

Is there a way to add transparency to a background-image using CSS3?

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 07:30

    If you are using an image tag to set the image, it can be easily changed using the CSS3 property "opacity".

    It is written like this:

    img {
        opacity: 0.4;
        filter: alpha(opacity = 40); /* For IE */
    }
    

    the value for opacity must be between 0 and 1. 0 being invisible and 1 being opaque.

    If you are applying the background image by using the CSS "background-image" property then you can still use the opacity to change the background image but it must be done in a different way.

    This is because the opacity value changes the opacity on the entire element when you only want the opacity changed on the background image.

    There is an easy way to work around this: just overlay the content over the image and wrap them in a common parent and apply the opacity change to only the background part:

    HTML

    CSS

    .translucent {
        opacity: 0.4;
        filter: alpha(opacity = 40); /* For IE */
    }
    #container {
        position: relative;
        width: 200px;
        height: 200px;
    }
    #background, #content {
        position: absolute;
        top: 0;
        left: 0;
    }
    #background {
        background-image: url(http://www.thisisfake.com);
    }
    

提交回复
热议问题