Html 基本 CSS - 如何在顶部使用半透明 DIV 覆盖 DIV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17859993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:30:16  来源:igfitidea点击:

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

csshtml

提问by TM23

I'm struggling to make this render right in my browser (Chrome). I have a wrapper holding all the elements of the HTML, and I want to have a DIV (lets call it div-1) that hold a image, and has a overlay div on top of it to the left, like I sketched in this picture...any quick solutions?

我正在努力在我的浏览器(Chrome)中正确地进行渲染。我有一个包含 HTML 的所有元素的包装器,我想要一个包含图像的 DIV(让我们称之为 div-1),并在它的顶部左侧有一个覆盖 div,就像我在这个图片...任何快速解决方案?

div bg with overlay semi transparent div

div bg 与叠加半透明 div

回答by marcvangend

Here's a pure CSS solution, similar to DarkBee's answer, but without the need for an extra .wrapperdiv:

这是一个纯 CSS 解决方案,类似于 DarkBee 的答案,但不需要额外的.wrapperdiv:

.dimmed {
  position: relative;
}

.dimmed:after {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
}

I'm using rgba here, but of course you can use other transparency methods if you like.

我在这里使用 rgba,但当然,如果您愿意,您可以使用其他透明度方法。

回答by General_Twyckenham

Using CSS3 you don't need to make your own image with the transparency.

使用 CSS3,您不需要使用透明度制作自己的图像。

Just have a div with the following

只需有一个带有以下内容的 div

position:absolute;
left:0;
background: rgba(255,255,255,.5);

The last parameter in background (.5) is the level of transparency (a higher number is more opaque).

背景 (.5) 中的最后一个参数是透明度级别(数字越大越不透明)。

Example Fiddle

示例小提琴

回答by DarkBee

.foo {
   position : relative;
}
.foo .wrapper {
    background-image : url('semi-trans.png');
    z-index : 10;
    position : absolute;
    top : 0;
    left : 0;
}

<div class="foo">
   <img src="example.png" />
   <div class="wrapper">&nbsp;</div>
</div>

回答by Andreas Krohn

For a div-Element you could just set the opacity via a class to enable or disable the effect.

对于 div 元素,您可以通过类设置不透明度以启用或禁用效果。

.mute-all {
   opacity: 0.4;
}

回答by Pat Cheung

Like the answer previous, but I'd put ::before, just for stacking purposes. If you want to include text over the overlay (a common use case), using ::before will should fix that.

就像之前的答案一样,但我会放 ::before,只是为了堆叠目的。如果你想在覆盖层上包含文本(一个常见的用例),使用 ::before 应该可以解决这个问题。

.dimmed {
  position: relative;
}

.dimmed:before {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
}