我正在尝试在背景图像和内容之间添加一个半透明层。但是没有显示任何层。我使用了z-index但没有工作。这里有解决方案吗?或者我需要制作绝对定位背景图像和背景颜色?
如果我使用z-index:-1它会落后于所有......如果我使用1,那么我会来到所有
<div class="bg">
<div class="mask"></div>
<div class="content">
<h2>Hello There</h2>
</div>
</div>
和Css代码是
.bg{
background: url('http://support.kaziwood.com/wp-content/uploads/2018/06/member-1.png') no-repeat;
height:200px;
}
.content{padding:70px 130px}
.mask{
background:#000;
position:absolute;
content:'';
width:100%;
height:100%;
left:0;
top:0;
opacity:0.3;
z-index:-1;
}
答案 0 :(得分:0)
您需要将position:relative
添加到父div
和内容div
。试试这个CSS代码。
.bg {
background: url('http://support.kaziwood.com/wp-content/uploads/2018/06/member-1.png') no-repeat;
height: 200px;
position: relative;
}
.content {
padding: 70px 130px;
position: relative;
}
.mask {
background: #000;
position: absolute;
content: '';
width: 100%;
height: 100%;
left: 0;
top: 0;
opacity: 0.3;
z-index: 0;
}
答案 1 :(得分:0)
您只需使用linear-gradient
作为图片的第二个背景:
.bg {
background:
linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)),
url('http://support.kaziwood.com/wp-content/uploads/2018/06/member-1.png') center/cover no-repeat;
height: 200px;
}
.content {
padding: 70px 130px
}
<div class="bg">
<div class="content">
<h2>Hello There</h2>
</div>
</div>
答案 2 :(得分:0)
这可以使用更少的元素和使用伪内容的简化结构来实现。
<div>
<h2>Hello, there</h2>
</div>
然后是CSS:
/* main container */
div {
background: url('my-pic.png') center/cover;
height:200px;
width: 400px;
position: relative;
text-align: center;
padding-top: 3em;
box-sizing: border-box;
}
/* pseudo content for overlay */
div::before{
content:'';
background:#000;
position:absolute;
content:'';
width:100%;
height:100%;
left:0;
top:0;
opacity:.3;
}
/* content - make sure it sits above overlay */
div > * { position: relative; z-index: 1; }
div h2 { color: white; }