简体   繁体   English

基本CSS - 如何在顶部覆盖半透明DIV的DIV

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

I'm struggling to make this render right in my browser (Chrome). 我很难在我的浏览器(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? 我有一个包含HTML的所有元素的包装器,我希望有一个DIV(让我们称之为div-1)来保存图像,并且在它的左上方有一个叠加div,就像我在这里勾画的那样图片...任何快速解决方案?

div bg with overlay semi transparent div

Here's a pure CSS solution, similar to DarkBee's answer, but without the need for an extra .wrapper div: 这是一个纯CSS解决方案,类似于DarkBee的答案,但不需要额外的.wrapper div:

.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,但是如果你愿意的话,你当然可以使用其他透明方法。

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 示例小提琴

.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>

For a div-Element you could just set the opacity via a class to enable or disable the effect. 对于div-Element,您可以通过类设置不透明度以启用或禁用效果。

.mute-all {
   opacity: 0.4;
}

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将解决这个问题。

.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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM