我试图制作一个简单的视差效果,但我也想为背景图像添加一个自定义的半透明颜色。
我尝试了很多解决方案,这个似乎工作,但颜色应用于儿童元素的顶部,即使我使用::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或者有同样的问题
你可以在z-index:-1和.spannerBg之前给你的.spannerBg ::一个z-index:1
之前的元素现在正在其兄弟姐妹身后。
.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>
我希望这有帮助:
.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>