这可能是一个新手问题,但我在任何地方都找不到答案。我正在编写一个带有视差背景图像的网站,并希望使所述图像有点透明,而不是上面的文本,这应该是完全不透明的。我遵循了 w3school 的模型(进行了一些更改(,考虑到背景图像是在父容器中定义的,因此文本继承了图像的不透明度,如bgimg-2
所示。
我试图做的,从摆弄样式表无济于事的地方,是创建一个封装背景和文本的新容器section-img
,这样它们的样式就不会相互重叠。然而,这使得图像的(bgimg-1
(高度等于0。
这是一个 MRE:
<!DOCTYPE html>
<html>
<style>
body, html {
height: 100%;
margin: 0;
background-color: #282828;
font-family: sans-serif;
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.section-img {
position: relative;
min-height: 100%;
}
.bgimg-1 {
background-image: url("https://i.redd.it/v3wjcf1p59841.jpg");
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
opacity: 1;
z-index: -1;
}
.bgimg-2 {
position: relative;
opacity: 0.6;
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
background-image: url("https://i.redd.it/o1a3xr4b39841.jpg");
min-height: 100%;
}
#title {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
text-align: center;
color: white;
font-size: 7vw;
letter-spacing: 2vw;
}
.section-text {
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 100%;
text-align: center;
font-weight: bold;
color: white;
letter-spacing: 2vw;
font-size: 3vw;
color: #f7f7f7;
}
</style>
<body>
<div class="section-img">
<div id="title">No background picture here!</div>
<div class="bgimg-1"></div>
</div>
<div class="bgimg-2">
<div class="section-text">I want different opacities :(</div>
</div>
</body>
</html>
实现这两个项目的不透明度差异的最合理方法是什么?
为什么不使用"rgba"样式(CSS 输入(,"rgb"将设置背景的颜色,"a"命令将设置图像的不透明度(透明度(,它可以设置在0-1之间,其中0是透明(0%不透明度(,1是100%不透明度。 我希望这有帮助!!
.bgimg-1 {
background-image: url("https://i.redd.it/v3wjcf1p59841.jpg");
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
opacity: 1;
// z-index: -1; // you won't need this
// add position relative so that the ::before position absolute will be in relation to it's parent and not the body:
position:relative;
}
// .bgimg-2 { // don't need this div
.bgimg-1::before { // add this instead
// position: relative; // no this instead:
position: absolute;
top:0; left: 0; right: 0; bottom: 0;
// end this instead //
opacity: 0.6;
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
background-image: url("https://i.redd.it/o1a3xr4b39841.jpg");
min-height: 100%;
}