代码:
doctype html>html lang=en>head> meta charset=utf-8> title>documenttitle> style> div{ width:300px; height: 300px; margin: 50px auto; line-height: 300px; text-align: center; background: red; color: #000; font-size: 30px; -webkit-opacity: 0.2; } style>head>body> div class=“wrap”> 我爱夏天 div>body>html>
解决方法一:
在div.wrap内再加一个div。作为蒙版,对其设置透明度的变化样式,并且让内容相对于wrap绝对定位,要记得给wrap设置相对定位!!
doctype html>html lang=en>head> meta charset=utf-8> title>documenttitle> style> .wrap{ width:300px; height: 300px; margin: 50px auto; position: relative; } .con{ width: 300px; height: 300px; background: red; -webkit-opacity: 0.2; } span{ position: absolute; top: 150px; left: 100px; font-size: 30px; color: #000; } style>head>body> div class=wrap> div class=con>div> span>我爱夏天span> div>body>html>
最后效果:
解决方法二:
用rgba()设置background的背景色和透明度样式。
style> div{ width:300px; height: 300px; margin: 50px auto; line-height: 300px; text-align: center; background: rgba(250,18,18,0.2); color: #000; font-size: 30px; } style>
最后效果:
可以明显看出使用css3的rgba()要方便很多,节省大量代码,文档结构也更加清晰,不过rgba()的兼容性问题也让让人头疼:
最后给出一个兼容性的解决方法:
.rgba { background: rgb(0,0,0); /*the fallback color,这里也可以使用一张图片来代替*/ background: rgba(0, 0, 0,0.5); -ms-filter: progid:dximagetransform.microsoft.gradient(gradienttype=1,startcolorstr=#80000000,endcolorstr=#80000000); /*filter for ie8 */ filter: progid:dximagetransform.microsoft.gradient(gradienttype=1,startcolorstr=#80000000, endcolorstr=#80000000); /*filter for older ies */ }