我正在尝试使div覆盖另一个div,以使背景图像显得更暗。它可以工作,但不是使图像变暗,而是使所有内容(例如文本)变暗。即使overlay div位于其他包含text元素的div之前
这是一个片段,显示正在发生的事情:
.header {
background: url("http://mediad.publicbroadcasting.net/p/wamc/files/201609/codingsnippet.jpg") no-repeat center center fixed;
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-repeat: no-repeat;
color: white;
width: 100%;
height: 100%;
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
width: 100%;
height: 100%;
background: rgba(0,0,0,.5);
opacity: 0.5;
}
.heading {
display: inline-block;
font-size: 3em;
}
.nav-item {
font-size: 1.3em;
float: right;
list-style-type: none;
padding: 0px 5px;
}
.nav-item > a {
color: white;
font-weight: bold;
display: block;
}
a {
color: black;
text-decoration: none;
}Run Code Online (Sandbox Code Playgroud)
<div class="header">
<div class="overlay"></div>
<div class="nav">
<!-- <img src="img/logo.png" alt="logo" class="logo"> -->
<li class="nav-item"><a href="https://jordanbaron.github.io">Home</a></li>
<li class="nav-item"><a href="#about" >About</a></li>
<li class="nav-item"><a href="#portfolio" >Portfolio</a></li>
<li class="nav-item"><a href="#contact">Contact</a></li>
</div>
<h1 class="heading" id="heading"></h1>
</div>Run Code Online (Sandbox Code Playgroud)
z-index任何元素的默认值为auto,这意味着它z-index从其父级获取它。在您的代码中,只有.overlay该类具有一个z-index并且将其设置为1,这意味着它将被放置在具有较低z-index的.nav元素(例如您的元素)的前面。
要解决此问题,您只需要为该类分配z-index更高1的.nav级别即可。请记住,只有定位的元素可以具有z-index,因此您应该执行以下操作:
.nav {
position: relative;
z-index: 2;
Run Code Online (Sandbox Code Playgroud)
您的代码段已修复:
.nav {
position: relative;
z-index: 2;
Run Code Online (Sandbox Code Playgroud)
.header {
background: url("http://mediad.publicbroadcasting.net/p/wamc/files/201609/codingsnippet.jpg") no-repeat center center fixed;
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-repeat: no-repeat;
color: white;
width: 100%;
height: 100%;
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
width: 100%;
height: 100%;
background: rgba(0,0,0,.5);
opacity: 0.5;
}
.heading {
display: inline-block;
font-size: 3em;
}
.nav-item {
font-size: 1.3em;
float: right;
list-style-type: none;
padding: 0px 5px;
}
.nav-item > a {
color: white;
font-weight: bold;
display: block;
}
a {
color: black;
text-decoration: none;
}
.nav {
position: relative;
z-index: 2;
}Run Code Online (Sandbox Code Playgroud)
您可能还需要考虑其他更清洁的使图像变暗的方法,例如CSS filter属性。