首先用一个“外层div”来包裹“半透明div”和“内容div”,切记“半透明div”和“内容div”是兄弟关系,然后利用 position:absolute、z-index、background-color、opacity、filter:alpha(opacity)等等样式,就能实现想要的效果。
代码如下:
<title>css实现div层背景半透明而内容不透明的效果</title> <head> <style> .container { width:500px; height: 200px; margin: 10px auto; } .floating-layer{ color: #154BA0; background: #ff0000; filter: Alpha(Opacity=40, Style=0); -moz-opacity:0.4; opacity: 0.4; position: absolute; width:500px; height: 200px; z-index:20; } .text { position: absolute; width:500px; height: 200px; text-align:center; z-index:30; } </style> </head> <body> <div class="container"> <div class="floating-layer"></div> <div class="text">背景半透明但文字内容不透明</div> </div> </body>
效果图:
