今天在做东西的时候用到了opacity,我发现子元素会继承父元素的opacity。
我找了一下其他人的解决方案,发现了一个比较靠谱的:
既然子元素必定会继承父元素的opacity,那么咱们就不让他们存在父子关系。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title></title>
<style type="text/css">
body{
background-color: #000;margin: 0;padding: 0;
}
.noOpacity{
width: 300px;
height: 250px;
background-color: #37a7d7;
color: #fff;
}
/*上面的是背景对比,以下是方法*/
.container {
width: 300px;
height: 250px;
color: #fff;
position:relative;
}
.content {
position:relative;
z-index:5;
width: 100%;
height: 100%;
overflow: hidden;
}
.background {
background-color: #37a7d7;
position:absolute;
top:0px;
left:0px;
width:100%;
height:100%;
z-index:1;
/*兼容IE7、8 */
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
filter: alpha(opacity=50);
opacity:.5;
}
</style>
</head>
<body>
<div class="noOpacity">我是用来作对比的</div>
<div class="container">
<div class="content">
<p>我是class为content的DIV</p>
<p>我的背景是class为background的背景</p>
<p>通过相对定位和绝对定位,我把class为background的DIV移动到了我的位置。</p>
<p>同时通过我的较大的z-index浮在了它的上面。 :)</p>
<p style="text-align:right">——刘龙(liulo)</p>
</div>
<div class="background"></div>
</div>
</body>
</html>
效果:

本文代码及结果来自博主:iulo
