按照css2之前的滤镜属性opacity,会继承到内容上,也就是说我们给一个div设置了opacity:0.5,div里的文字也会出现半透明效果。点此查看Demo。
为了避免这种情况发生,我们不得不多增加一个div,用来透明背景,而另外一个放内容的div就不设背景,只要这2个div大小坐标保持一致,且放内容的div显示在透明背景的div上就达到效果了,点此查看Demo。
Demo代码:
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" />
< title >无标题文档 </ title >
< style type ="text/css" >
<!--
p { margin : 0px ; padding : 0px ; }
.imgDiv {
position : relative ;
width : 300px ;
border : 1px #FF6600 solid ;
}
.imgDiv img {
vertical-align : middle ;
}
.imgDiv p {
position : absolute ;
bottom : 0px ;
left : 0px ;
width : 100% ;
color : #FFFFFF ;
font-size : 14px ;
line-height : 40px ;
text-indent : 1em ;
}
.opacity {
position : absolute ;
bottom : 0px ;
left : 0px ;
width : 100% ;
height : 40px ;
background : #000000 ;
opacity : 0.4 ;
filter : alpha(opacity=40) ;
}
-->
</ style >
</ head >
< body >
< div class ="imgDiv" >
< img src ="http://www.caoren.net/pic/20101107/20101107css.jpg" width ="300" height ="450" />
< div class ="opacity" ></ div >
< p >这个肯定是美女 </ p >
</ div >
</ body >
</ html >
大家比较这2个demo就可以看出效果。
现在有了css3的rgba这个属性,就不用这么麻烦了,当然这也得要浏览器支持才行。一般童鞋们定义颜色都是用十六进制表示。如:background:#000000,表示背景色为黑色。当然也可以用RGB三原色值表示,如:background:rgb(0,0,0),也表示背景色为黑色。rgba只是在rgb的基础上增加了一个a,这个a表示透明度。而且这个属性不会被子元素继承下去,可以在定义颜色的属性使用,如:
.test{background:rgba(0,0,0,0.5)} //表示背景色黑色且半透明
.test{color:rgba(0,0,0,0.5)} //表示字体颜色为黑色且半透明
</style>
这样我们要实现背景透明内容不透明就不必增加一个div了,但是ie目前的版本都不支持该属性(不知道ie9是否支持),所以我增加一个ie条件注释,就是在ie下还是用上面的方法。测试通过环境:ff3.6,safari5,ie6,7,8。
点此查看完整Demo。
Demo代码:
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" />
< title >无标题文档 </ title >
< style type ="text/css" >
<!--
p { margin : 0px ; padding : 0px ; }
.imgDiv {
position : relative ;
width : 300px ;
border : 1px #FF6600 solid ;
}
.imgDiv img {
vertical-align : middle ;
}
.imgDiv p {
position : absolute ;
bottom : 0px ;
left : 0px ;
width : 100% ;
color : #FFFFFF ;
font-size : 14px ;
line-height : 40px ;
text-indent : 1em ;
background : rgba(0,0,0,0.4) ;
}
.opacity {
position : absolute ;
bottom : 0px ;
left : 0px ;
width : 100% ;
height : 40px ;
background : #000000 ;
filter : alpha(opacity=40) ;
}
-->
</ style >
</ head >
< body >
< div class ="imgDiv" >
< img src ="http://www.caoren.net/pic/20101107/20101107css.jpg" width ="300" height ="450" />
<!-- [if lte IE 8]>
<div class="opacity"></div>
<![endif] -->
< p >这个肯定是美女 </ p >
</ div >
</ body >
</ html >
转自:http://www.caoren.net/article/?id=22
个人收藏学习用