如何更改元素的不透明度/透明度并保持body背景图像仍然可见?



我是编码新手,在这里要问的第一个问题。

这是我第一次无法在网上找到答案,可能是因为我无法很好地解释/描述它。但是在这里我可以发布一张照片。

正是我想要做的。元素的这种深色背景,但要保持身体背景仍然可见

你能帮我如何在 CSS 中做到这一点吗?

非常感谢!

您可以为元素设置背景:背景颜色: RGBA(0,0,0,0.5);注意0.5。它从 0 运行到 1。越高越暗。

  • 创建具有绝对位置的div
  • 将其背景色设置为黑色
  • 将其不透明度设置为 0.5(根据需要调整不透明度这决定了您的透明度级别)。

html{
      width:100%,height:100%;
      }
    body{ 
      background-image: url(https://i.stack.imgur.com/wwy2w.jpg);
      height:100%;
      width:100%;
      background-size:cover;
      }
#black-box{
  position:absolute;
  background-color:black;
  opacity:0.5;
  width:50%;
  top:10%;
  left:10%;
  height:50%;
  }
<body>
      <div id="black-box"></div>
    </body>

您需要一个用于我添加的背景图像的div,然后您需要另一个div 以便垂直对齐内容,类似于您的示例,最后是第三个div 来保存内容。

.HTML:

<div class="background">
   <div class="background-module">
      <div class="background-info">
          <h1>Hello</h1>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris non imperdiet enim. Aenean eget dolor in risus aliquam pellentesque. Ut porta nec ex vel tincidunt. Maecenas varius accumsan posuere. Donec non blandit ipsum. Duis vel eros nunc. Donec aliquam ac ipsum et ultrices.</p>
          <form>
            <input type="email" />
            <button type="submit">Submit</button>
          </form>
       </div>
    </div>
</div>

.CSS:

.background {
  background:url("https://9to5mac.files.wordpress.com/2016/06/sierra-2.jpg?quality=82&strip=all") no-repeat center top;
  background-size: cover;
  height:800px; /* this can be anything */
  display:table; /* required to vertically align the content */
  width:100%;
}
.background-module {
  display:table-cell; /* required to vertically align the content */
  vertical-align:middle; /* required to vertically align the content */
}
.background-info {
  background:rgba(0, 0, 0, 0.5); /* required to create the opacity look in your example */
  padding: 15px;
  text-align: center;
  width:50%;
  margin:0 auto;
}

这是一个工作小提琴> https://jsfiddle.net/czy5ycsr/的链接

你可以试试这样的东西

.HTML:

<div class="container">
  <div class="inner">
    <div class="content">
      <p>Content</p>
      <div class="overlay"></div>
    </div>    
  </div>
</div>

.CSS:

.container {
  width:1400px;
  background: white url(http://lorempixel.com/1400/1200/nature/1/) no-repeat center;
  height: 400px;
  padding: 50px 0;
  margin : 20px auto;
}
.content {
  display:block;
  width: 50%;
  height: 200px;
  background:transparent;
  margin: 0 auto;
  position:relative;
}
.overlay {
  width:100%;
  height:200px;
  background: rgba(0,0,0,0.7);
  position:absolute;
  left:0;
  top:0;
  z-index: 0;
}
p {
  padding: 20px;
  color: #FFFFFF;
  position: relative;
  z-index: 1;
}

最新更新