目录
一、问题描述
如下:为27,28,29,30设置了opacity:0.4;
,元素半透明展示。当元素上方的下拉框展示出来时,覆盖这一部分的下拉框也半透明了!
二、让下拉部分不透明的方法:
假设希望展示在顶层且不透明的是元素a,底部透明部分是元素b。
方法生效前提:元素a不能是元素b的子元素,即元素a,b不可以是嵌套结构。
第一步:让a元素脱离文档流,采用position: absolute;
【属性为absolute、relative、fixed均可。但float不可以。】
第二步:设置a元素图层在最上方(大于b元素的z-index即可),z-index: 10;
第三步:设置a元素背景为白色,background-color: #fff;
.a {
position: absolute;
background-color: #fff;
z-index: 10;
}
实施后的效果:
通过基础代码复现(仿写日历的代码过于复杂,这里使用基础代码展示。重点代码部分在.top1{}中)
<!DOCTYPE html>
<html>
<head>
<style>
/* 半透明部分样式设置 */
.opacity-bottom {
position: relative;
width: 200px;
height: 200px;
color: #fff;
background-color: #1e80ff;
opacity: 0.5;
z-index: 1;
}
#parent {
position: relative;
}
/* 设置展示在顶层的绿色方块 */
.top1 {
position: absolute;
top: 22px;
width: 80px;
height: 80px;
background-color: lightseagreen;
z-index: 10;
}
/* 设置展示在顶层的白色方块 */
.top2 {
position: fixed;
top: 30px;
left: 120px;
width: 80px;
height: 80px;
color: #000;
background-color: #fff;
z-index: 10;
}
/* 底部的颜色对照方块 */
.normal-blue {
float: left;
width: 100px;
height: 20px;
background-color: #1e80ff;
}
.normal-green {
float: left;
width: 100px;
height: 20px;
background-color: lightseagreen;
}
</style>
</head>
<body>
<div id="parent">
<div class="opacity-bottom">
我是底部半透明部分 我是底部半透明部分 我是底部半透明部分
我是底部半透明部分 我是底部半透明部分 我是底部半透明部分
我是底部半透明部分 我是底部半透明部分 我是底部半透明部分
我是底部半透明部分
</div>
<!-- top1,top2不是半透明元素的子元素 -->
<div class="top1">可以盖住可以盖住可以盖住可以盖住可以盖住</div>
<div class="top2">可以盖住可以盖住</div>
<div class="normal-blue"></div>
<div class="normal-green"></div>
正常黑色字
</div>
</body>
</html>
三、方法缺陷
当希望不透明的元素a,作为半透明元素b的子元素时,如上设置后,内容虽然可以覆盖底部元素b,元素a的背景色及文字还是会继承父元素的半透明性质。
如下:浅蓝色部分设置了opacity:0.5;
,浅绿色部分是浅蓝色部分的子元素,在设置了position: relative; background-color: lightseagreen;z-index: 10px;
后,依然半透明。底部两个色块是蓝色和绿色不透明时的颜色。
<!DOCTYPE html>
<html>
<head>
<style>
.opacity-bottom {
width: 200px;
height: 200px;
color: #fff;
background-color: #1e80ff;
opacity: 0.5;
}
.top1 {
position: relative;
top: -30px;
width: 80px;
height: 80px;
background-color: lightseagreen;
z-index: 10px;
}
.top2 {
position: absolute;
top: 20px;
left: 100px;
width: 80px;
height: 80px;
color: #000;
background-color: #fff;
z-index: 10px;
}
.normal-blue {
width: 100px;
height: 20px;
background-color: #1e80ff;
}
.normal-green {
width: 100px;
height: 20px;
background-color: lightseagreen;
}
</style>
</head>
<body>
<div id="parent">
<div class="opacity-bottom">
我是底部半透明部分 我是底部半透明部分 我是底部半透明部分
我是底部半透明部分 我是底部半透明部分 我是底部半透明部分
我是底部半透明部分 我是底部半透明部分 我是底部半透明部分
我是底部半透明部分
<div class="top1">可以盖住可以盖住可以盖住可以盖住可以盖住</div>
<div class="top2">可以盖住可以盖住</div>
</div>
<div class="normal-blue"></div>
<div class="normal-green"></div>
正常黑色字
</div>
</body>
</html>
两元素嵌套情况下的解决办法
如果仅希望背景半透明,且结构最好是父元素子元素嵌套,可以通过rgba()将父元素背景设置为半透明颜色background: raba(x1, x2, x3, y);
其中:
- x1 x2 x3 取值是
0-255
之间的整数 - y取值是0-1之间
(0,0.1,0.2, 0.3,0.4, 0.5,0.6,0.7,0.8,0.9,1)
IE的话可以用滤镜,filter:alpha()
四、参考链接
-
解决方法来自百度日历,通过F12可以查看百度日历源代码
-
仅设置背景半透明的参考链接: CSS常见问题解决002——opacity将子元素都变透明了https://blog.csdn.net/tongbiaos/article/details/52305538