Search code examples
cssinternet-explorer-8opacity

Opacity of div's background without affecting contained element in IE 8?


I want to set Opacity of div's background without affecting contained element in IE 8. have a any solution and don't answer to set 1 X 1 .png image and set opacity of that image because I am using dynamic opacity and color admin can change that

I used that but not working in IE 8

#alpha {
    filter: alpha(opacity=30);
    -moz-opacity: 0.3;
    -khtml-opacity: 0.3;
    opacity: 0.3;
}

and

rgba(0,0,0,0.3)

also.


Solution

  • The opacity style affects the whole element and everything within it. The correct answer to this is to use an rgba background colour instead.

    The CSS is fairly simple:

    .myelement {
        background: rgba(200, 54, 54, 0.5);
    }
    

    ...where the first three numbers are the red, green and blue values for your background colour, and the fourth is the 'alpha' channel value, which works the same way as the opacity value.

    See this page for more info: http://css-tricks.com/rgba-browser-support/

    The down-side, is that this doesn't work in IE8 or lower. The page I linked above also lists a few other browsers it doesn't work in, but they're all very old by now; all browsers in current use except IE6/7/8 will work with rgba colours.

    The good news is that you can force IE to work with this as well, using a hack called CSS3Pie. CSS3Pie adds a number of modern CSS3 features to older versions of IE, including rgba background colours.

    To use CSS3Pie for backgrounds, you need to add a specific -pie-background declaration to your CSS, as well as the PIE behavior style, so your stylesheet would end up looking like this:

    .myelement {
        background: rgba(200, 54, 54, 0.5);
        -pie-background:  rgba(200, 54, 54, 0.5);
        behavior: url(PIE.htc);
    }
    

    [EDIT]

    For what it's worth, as others have mentioned, you can use IE's filter style, with the gradient keyword. The CSS3Pie solution does actually use this same technique behind the scenes, but removes the need for you to mess around directly with IE's filters, so your stylesheets are much cleaner. (it also adds a whole bunch of other nice features too, but that's not relevant to this discussion)