如何使用一个div作为覆盖层盖在另一个div上方

4

大家好,我想在一个

区域
上叠加另一个
覆盖层
,我已经查看了类似的帖子,但是没有一个解决我的具体需求。通过我的测试,它只出现在主
区域
下面。容器
阅读器
具有固定的位置,这是我能够填满整个屏幕的唯一方式。请查看我的代码如下。谢谢!

 <style>
    html,
    body {
       box-sizing: border-box;
       min-height: 100%;
       margin: 0;
       padding: 0;
    }

    #reader {
       position: fixed;
       width:100%;
       height: 100%;
       top: 10;
       left: 20;
       bottom: 10;
       right: 20;
       background: wheat;
       display: flex;
       flex-direction: column;
    }

    #reader #toolbar {
      flex: 0 1 auto;
      display: flex;
      justify-content: space-between;
      background: rgba(0,0,0,0.05);
      padding: 10px;
    }

    #reader #toolbar .left {
      flex: 0 1 auto;
    }

    #reader #toolbar .center {
      flex: 0 1 auto;
    }

    #reader #toolbar .right {
      flex: 0 1 auto;
    }

   .area {
      flex: 1 0 auto;
      display: flex;
      margin: 10px 15px;
      padding: 10px;
    }

    #reader #area div {
      position: absolute;
      width: 90%;
      top: 10px;
      left: 5%;
      bottom: 10px;
      right: 5%;
    }

    .cover {
      z-index: 9;
    }

  </style>

  <div id="reader">
     <input type="file" id="bookChooser">
     <select id="toc"></select>
     <div id="area" class="area"></div>
     <div class="area cover"></div> <!-- This should cover the div area above, not pushed down -->
     <button id="prev" type="button"><</button>
     <button id="next" type="button">></button>
  </div>
3个回答

8

将两个 div 放在一个根 div 中,然后给根 div 设置 position:relative,并让覆盖层的 div 绝对定位,设置固定的高度和宽度,并在覆盖层的 div 上应用 display:block。如果仍然不起作用,则应用 z-index

应该像这样:

HTML:
<div class="parent">
     <div id="area" class="area"></div>
     <div class="area cover"></div>
</div>

CSS:

.parent{
  position: relative;
  height:200px;
  width: 200px;
}
.cover{
  position: absolute;
  height: 100%;
  width: 100%;
  display: block;
  z-index: 999;
}

希望这对您有用。


感谢@Sudipta Das的回复,实际上父级div必须是100%的宽度和高度,我会尝试您的代码并与您联系。谢谢。 - Timothy Ayodele

0

M8,

position fixed - 将元素固定到屏幕视图上。 如果您想通过 div2 覆盖例如 div1,则应将 div2 放入 div1 中,然后将 div1 的位置设置为相对位置,这将允许您将 div2 的位置绝对设置,并且它将在其上方。如果您将某些内容设置为绝对位置,则需要有一些参考物,该参考物是具有相对位置的父元素,或者最后是 BODY(如果存在任何相对父元素)。

另一个解决方案是:如果您的 div1 具有已知高度,则可以在 DIV2 上使用 margin-top(减去)-HEIGHTofDIV1 px,这将将其移动到顶部并覆盖 div1。


感谢@szymanskicode的回复,我会尝试并回复您。 - Timothy Ayodele

0

你可以将“cover”作为“area”的子元素

<div id="area" class="area">
  <div class="cover"></div>
</div>

.area {
  position: relative;
  flex: 1 0 auto;
  margin: 10px 15px;
  padding: 10px;
}

.area .cover {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: #000;
  opacity:0.5;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接