继承背景颜色的子元素

Child elements inheriting background color

我正在尝试制作简单的视差效果,但是我还想向背景添加自定义半透明颜色图片。

我尝试了很多解决方案,这个似乎可行,但是即使我使用 ::before 选择器,颜色也会应用到子元素的 顶部 上。

.spannerBg {
 background-attachment: fixed;
 background-position: center;
 background-repeat: no-repeat;
 background-size: cover;
 position: relative;
 background-color: rgba(255, 150, 0, 0.5);
 min-height: 300px;
}

.spannerBg::before {
 content: "";
 display: block !important;
 background-color: inherit;
 position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 height: 100%;
}

p {
  font-size: x-large;
}
<div class="spannerBg" style="
    color: #fff;
    background-color: rgba(0, 0, 0, 0.5);
    background-image:url(https://images.pexels.com/photos/1051075/pexels-photo-1051075.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)">
  
  <p>Somecontent</p>

</div>
<div>
  beiwrfa<br>ewnifiebfia<br>fbjwqbfwebfj<br>
</div>
<div class="spannerBg" style="
    background-image:url(https://images.pexels.com/photos/865711/pexels-photo-865711.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)">
    <p>Somecontent</p>
</div>

<div>
  <p>somecontent</p>
</div>

我看到一些关于使用半透明 png 或假 div 但我希望它是 100% css。

我也看到了this question,但是所有答案似乎都不是css或者有同样的问题

希望对您有所帮助:

.spannerBg {
background-attachment: fixed;
 background-position: center;
 background-repeat: no-repeat;
 background-size: cover;
 position: relative;
 min-height: 300px;
}

.spannerBg::before {
 content: "";
 display: block !important;
 background-color: inherit;
 position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 height: 100%;

}
<div class="spannerBg" style="
background-image: linear-gradient( rgba(255, 150, 0, 0.5), rgba(255, 150, 0, 0.5) ), url(https://images.pexels.com/photos/865711/pexels-photo-865711.jpeg);
">
    <p>Somecontent</p>
</div>

你可以给你的 .spannerBg::before 一个 z-index: -1.spannerBg一个z-index:1

before 元素现在移到其兄弟元素后面。

.spannerBg {
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  background-color: rgba(255, 150, 0, 0.5);
  min-height: 300px;
  z-index: 1;
}

.spannerBg::before {
  content: "";
  display: block !important;
  background-color: inherit;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

p {
  font-size: x-large;
}
<div class="spannerBg" style="
    color: #fff;
    background-color: rgba(0, 0, 0, 0.5);
    background-image:url(https://images.pexels.com/photos/1051075/pexels-photo-1051075.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)">

  <p>Somecontent</p>

</div>
<div>
  beiwrfa<br>ewnifiebfia<br>fbjwqbfwebfj<br>
</div>
<div class="spannerBg" style="
    background-image:url(https://images.pexels.com/photos/865711/pexels-photo-865711.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)">
  <p>Somecontent</p>
</div>

<div>
  <p>somecontent</p>
</div>