首页 > 解决方案 > 在不透明的 div 上创建一个透明的 div

问题描述

我有 3 个 div :

我希望最终的 div (DIV3) 完全透明,以便它显示绿色的 (DIV1),就像红色 div (DIV2) 中的“洞”。

body,
html {
  width: 100%;
  height: 100%;
}

#div1 {
  background: rgb(0, 255, 0);
  width: 100%;
  height: 100%;
}

#div2 {
  background: rgba(255, 0, 0, 0.5);
  width: 100%;
  height: 100%;
}

#div3 {
  position: absolute;
  width: 50px;
  height: 50px;
  left: 50%;
  background: rgba(0, 0, 255, 0.5);
}
<div id="div1">
  <div id="div2">
    <div id="div3">
    </div>
  </div>
</div>

基本上,最终的 div (DIV3) 将完全“取消”红色父 div (DIV2) 的不透明度。

可能吗 ?

编辑 1: 像这样的东西:

在此处输入图像描述

编辑 2:

像这样的东西会起作用,但我需要在每次调整大小时通过 js 手动设置宽度,以便正确覆盖屏幕:

position: absolute;
border: solid rgba(255,0,0,0.5);
border-top-width: 50px;
border-bottom-width: 50px;
border-left-width: 50px;
border-right-width: 50px;

标签: htmlcss

解决方案


这可能是一个简单的解决方法。检查它是否适用于您的目的:

div {
  background-image: url(http://placekitten.com/1200/800);
  height: 100vh;
  width: 100vw;
}

div > div {
  background: transparent;
  border: 60px solid rgba(200, 0, 0, .9);
  position: absolute;
  width: 30%;
  height: 30%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div><div></div></div>


推荐阅读