内容和背景图像之间的半透明层 - CSS

时间:2018-06-03 16:08:39

标签: html css

我正在尝试在背景图像和内容之间添加一个半透明层。但是没有显示任何层。我使用了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;
}

https://jsfiddle.net/2kcx1L2n/

3 个答案:

答案 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)

这可以使用更少的元素和使用伪内容的简化结构来实现。

Fiddle

<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; }