我正在尝试制作一个覆盖另一个 div 的 div 以使背景图像显得更暗。它有效,但不是使图像变暗,而是一切都变暗,例如文本。即使覆盖 div 位于其中包含文本元素的其他 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;
}
<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>
最佳答案
任何元素的默认 z-index
都是 auto
,这意味着它从其父级获取其 z-index
。在你的代码中,只有 .overlay
类有一个 z-index
并且它被设置为 1
,这意味着它将被放在前面具有较低 z-index 的元素,例如 .nav
元素。
要解决此问题,您只需为 .nav
类分配一个高于 1
的 z-index
。请记住,只有定位元素可以有一个 z-index
,所以你应该这样做:
.nav {
position: relative;
z-index: 2;
您的代码段已修复:
.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;
}
<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>
您可能还想考虑其他更简洁的方法来使图像变暗,例如 CSS filter
属性。
关于html - CSS Overlay 使文本变暗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54412613/