首页 > 解决方案 > CSS:如何将子图像放在父背景图像前面?

问题描述

.section在 CSS 中的类上设置了背景图像。在这一点上,我也有不透明性。我的孩子img是一个透明的 png,但是它显示在 div 的背景图像后面,并且它还继承了我在背景图像上的不透明度。我怎样才能把它带到顶峰?我尝试使用 z-indexes 但它没有解决它。

.section {
  background-size: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  background-image: url(/image/bg.png);
  background-repeat: no-repeat;
  position: relative;
}
.section:before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-image: linear-gradient(to bottom right, #000000, #000000);
  opacity: 0.6;
}

.logo {
  width: 100%;
}
<div class="section">
  <img class="logo" src={ "imgafi2x.png"}/>
</div>

标签: htmlcss

解决方案


只需使用以下代码:

注意:我没有添加代码片段,因为它是 React 和 SCSS。Stack Snippets 不支持 React 和 SCSS。这就是我链接到 JSBin 的原因。

.section {
  background-size: 100%;
  background-color: rgba(0,0,0,0.5);
  background-image: url(//placehold.it/500?text=BG);
  background-repeat: no-repeat;
  position:relative;
  &:before {
    content: ' ';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-image: linear-gradient(to bottom right,#000000,#000000);
    opacity: .6; 
    z-index: 1;
  }
  .logo {
    width: 100%;
    position: relative;                 /* Change Here */
    z-index: 2;                         /* Change Here */
  }
}

预习

预习

小提琴: http: //output.jsbin.com/lepahirifa


推荐阅读