想要在背景图像上创建一个透明的彩色覆盖层,但想要覆盖层前面的所有内容



基本上,我想要一个背景,然后是一个透明的覆盖层,然后把我所有的内容都放在最前面。到目前为止,我有

#overlay{
    position:absolute;
    left:0;
    right:0;
    top:0;
    bottom:0;
    background-color:grey;
    opacity:0.5;
    }

我的html文档中的所有内容都有一个<div id="overlay">。提前谢谢。

这是一种简单的方法:

body {
  width: 100%;
  height: 100%;
}
.content {
  position: relative;
  width: 500px;
  height: 500px;
  background-image: url('http://static.vecteezy.com/system/resources/previews/000/094/491/original/polygonal-texture-background-vector.jpg');
  background-size: cover;
}
.overlay {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}
.inner-content {
  width: 250px;
  height: 250px;
  padding: 20px;
  background-color: #FFFFFF;
  margin: 50px 0 0 105px;
  color: #000000;
}
<div class="content">
  <div class="overlay">
    <div class="inner-content">Your inner content</div>
  </div>
</div>

这个示例有很多不必要的代码,只是为了让示例看起来好看,但你应该明白这一点。

我会使用ios答案,但使用:before来消除不必要的覆盖div:

body {
  width: 100%;
  height: 100%;
}
.content {
  position: relative;
  width: 500px;
  height: 500px;
  background-image: url('http://static.vecteezy.com/system/resources/previews/000/094/491/original/polygonal-texture-background-vector.jpg');
  background-size: cover;
  padding: 50px;
}
.content:before{
  content: ' ';
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}
.inner-content {
  width: 250px;
  height: 250px;
  padding: 20px;
  background-color: #FFFFFF;
  color: #000000;
  position: absolute;
}
<div class="content">
  <div class="inner-content">Your inner content</div>
</div>

最新更新