css 设置元素背景为透明

要设置某一元素的背景为透明,在 chrome 、firefox、opera 下是这样的:

[css]

background-color: rgba(0, 0, 0, 0.4);

rgba 中的最后一个参数 0.4 就是想要的透明度,范围在0~1之间。

在 ie 中一般是这样的:
[css]
background-color: rgb(0, 0, 0);
filter: alpha(opacity=40);
opacity 表示透明度,它的值范围在 0~100 之间

那么如何兼容各浏览器呢?只要把它们写在一起就行了。
由于 ie 不支持 rgba,所以会忽略之。其他浏览器对于自己不支持的,一般也会忽略。
下面来个示例:
HTML 代码:

[html] 
<body> 
    <p class="non-transparent"> 
        aaaaa 
        </p> 
    </body> 
     
<p class="transparent"> 
    <p class="box"> 
        box 
        </p> 
    </p>

CSS 代码:

[css] 
.non-transparent:hover { 
    background-color: yellow; 
} 
 
.transparent { 
    position: absolute; 
    top: 0; 
    left: 0; 
     
    text-align: center; 
     
    width: 100%; 
    height: 100%; 
     
    filter: alpha(opacity=40); 
    background-color: rgb(0, 0, 0); 
     
    background-color: rgba(0, 0, 0, 0.4); 
} 
 
.box { 
    background-color: yellow; 
    width: 50%; 
    height: 50%; 
     
    position: relative; 
    left: 5%; 
    top: 10%; 
}

显示效果:

chrome:

firefox:

opera:

ie8:

另外,在 chrome、firefox、opera 中也可以这样:
opacity: 0.4;
但是这样的话,会把所有子元素的透明度也设置为同样的值,效果如下图:

css 设置元素背景为透明

相关文章:

你感兴趣的文章:

标签云: