Parent div transparent background but not affect child div transparency

狂风中的少年 提交于 2019-12-17 14:02:14

问题


<div class="container">
    <div class="site_content">
        some stuff, images etc
    </div>
</div>


.container{
    background-color:#333;
    }

What I'd like is to have the .container div to have opacity of 80%, but the content of .site_content to be at 100%

Setting css opacity affects all child elements. Is there a way do this? With jQuery?

Because of how this will be used, I'd prefer to avoid the technique of positioning another transparent div behind to achieve the effect.


回答1:


You need to use the RGBA background property on the container div. background: rgba(64, 64, 64, 0.5). 64, 64, 64 are the RGB color values. and 0.5 is the opacity value. Now parent can have it's own opacity value not affecting children. This is fully supported by FireFox, Opera, Chrome, Safari and IE9.

Check working example at http://jsfiddle.net/Rp5BN/

To support IE 5.5 to 8 we need to use vendor-specific CSS 'gradient filter:' So you need to add this.

filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#7f404040, endColorstr=#7f404040);

Where 7f represents 127, i.e. 50% opacity and 404040 is the color.

Check working example in IE http://jsfiddle.net/Rp5BN/2/




回答2:


The most reasonable solution is:

.alpha60 {
    /* Fallback for web browsers that doesn't support RGBa */
    background: rgb(0, 0, 0);
    /* RGBa with 0.6 opacity */
    background: rgba(0, 0, 0, 0.6);
    /* For IE 5.5 to 7*/
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
    /* For IE 8*/
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)"; 
}


来源:https://stackoverflow.com/questions/5148128/parent-div-transparent-background-but-not-affect-child-div-transparency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!