用opacity设置元素背景的透明度

老白 3个月前 192浏览 0评论

一、设置元素背景透明度

opacity可以用来设置元素背景的透明度;它需要0~1之间的值

0表示完全透明(opacity:0);

1表示完全不透明(opacity:1);

0.5表示半透明(opacity:0.5);

代码演示:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>opactity</title>
    <style>
    .box1{
                position:relative;
        width:200px;height:200px;
        background-color: #00f;
    }
         .box2{
              position:absolute;
              top:80px;
              left:80px;
              width:200px;
              height:200px;
              background-color:#0f0;
       }
       .box3{
             position:relative;
              width:200px;
              height:200px;
              background-color:#f00;
              z-index:1;
}
</style>
</head>
<body>
    <div></div>
       <div></div>
       <div></div>
</body>
</html>

对比一下元素在设置同名之前的表现效果:

设置透明度的效果

.box1{
                 position:relative;
             width:200px;height:200px;
            background-color: #00f;
            z-index:10;
            opacity:0.5;
     }
          .box2{
               position:absolute;
               top:80px;
               left:80px;
               width:200px;
               height:200px;
               background-color:#0f0;
               z-index:5;
               opacity:0.5;
        }
        .box3{
               position:relative;
               width:200px;
               height:200px;
              background-color:#f00;
             z-index:1;
               opacity:0.5;
 }

表现效果:

 

 

二、浏览器兼容性问题:

 


 opacity属性在IE8及其以下的浏览器中不支持

 


 

为了实现透明效果,IE8及其以下的浏览器需要使用如下标签代替:

alpha(opacity=透明度)

透明度选择一个0~100之间的值

0表示完全透明(filter:alpha(opacity=0);)

100表示完全不透明(filter:alpha(opacity=100);)

50表示半透明(filter:alpha(opacity=50);)

这种方式支持IE6

filter:alpha(opacity=50);

.box1{
                position:relative;
        width:200px;height:200px;
        background-color: #00f;
                z-index:10;
                opacity:0.5;
                filter:alpha(opacity=10);
    }
.box2{position:absolute;
      top:80px;
      left:80px;
      width:200px;
      height:200px;
      background-color:#0f0;
      z-index:5;
      opacity:0.5;
      filter:alpha(opacity=50);}
.box3{
      position:relative;
      width:200px;
      height:200px;
      background-color:#f00;
      z-index:1;
opacity:0.5;
filter:alpha(opacity=80)}

表现效果:在IE8及其以下的浏览器也可以很好地适应

 

 因为filter:alpha(opacity=透明度)  这条元素写在下面,所以  filter:alpha(opacity=透明度)  的优先级要高于 opacity:0.5;  的优先级。最终表现效果不是opacity:0.5


发表评论