Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background image transparency with CSS3?

Tags:

css

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

like image 502
Alice Avatar asked Jan 01 '12 05:01

Alice


1 Answers

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

<div id="container">
    <div id="background" class="translucent"></div>
    <div id="content"></div>
</div>

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);
}
like image 77
Mark Kramer Avatar answered Oct 14 '22 19:10

Mark Kramer