css 设置元素背景为透明

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

[css] view plain copy
 background-color: rgba(0, 0, 0, 0.4);  

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

在 ie 中一般是这样的:

[css] view plain copy
 background-color: rgb(0, 0, 0);  

filter: alpha(opacity=40);  

opacity 表示透明度,它的值范围在 0~100 之间

那么如何兼容各浏览器呢?只要把它们写在一起就行了。

由于 ie 不支持 rgba,所以会忽略之。其他浏览器对于自己不支持的,一般也会忽略。

下面来个示例:

HTML 代码:

[html] view plain copy
 <body>  
  1.         aaaaa  
  2. </div>  
  3. </body>  
  4. <div class="transparent">  
  5. <div class="box">  
  6.         box  
  7. </div>  
  8. </div>  


CSS 代码:

[css] view plain copy
 
    1. .non-transparent:hover {  
    2.     background-color: yellow;  
    3. }  
    4.   
    5. .transparent {  
    6.     position: absolute;  
    7.     top: 0;  
    8.     left: 0;  
    9.       
    10.     text-align: center;  
    11.       
    12.      100%;  
    13.     height: 100%;  
    14.       
    15.     filter: alpha(opacity=40);  
    16.     background-color: rgb(0, 0, 0);  
    17.       
    18.     background-color: rgba(0, 0, 0, 0.4);  
    19. }  
    20.   
    21. .box {  
    22.     background-color: yellow;  
    23.      50%;  
    24.     height: 50%;  
    25.       
    26.     position: relative;  
    27.     left: 5%;  
    28.     top: 10%;  
    29. }