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]
  1. <body>  
  2.     <div class="non-transparent">  
  3.         aaaaa  
  4.         </div>  
  5.     </body>  
  6.       
  7. <div class="transparent">  
  8.     <div class="box">  
  9.         box  
  10.         </div>  
  11.     </div>  


CSS 代码:

[css] 
 
  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.     width: 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.     width: 50%;  
  24.     height: 50%;  
  25.       
  26.     position: relative;  
  27.     left: 5%;  
  28.     top: 10%;  
  29. }  


显示效果:

 

chrome:

firefox:

opera:

ie8:

 

另外,在 chrome、firefox、opera 中也可以这样:

opacity: 0.4;

但是这样的话,会把所有子元素的透明度也设置为同样的值,效果如下图:

posted @ 2015-05-26 11:12  欲望灬IT小菜  阅读(1672)  评论(0编辑  收藏  举报