当前位置:Gxlcms > css > css设置元素背景为透明

css设置元素背景为透明

时间:2021-07-01 10:21:17 帮助过:77人阅读

要设置某一元素的背景为透明,在 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 代码:

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

CSS 代码:

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

显示效果:

20140808174213906.png

chrome:

firefox:

20140808174213906.png

opera:

20140808174213906.png

ie8:

20140808174213906.png

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

20140808174213906.png

人气教程排行