首页 > 解决方案 > 如何使模态在其父 div 之外打开

问题描述

我在父 div 中设置了一个带有打开按钮的弹出模式,但是当它打开时,它包含在 div 中,我希望它在所有 div 之上打开。

我尝试将 z-index 设置为高于父 div,但似乎没有什么不同。我怀疑它与父 div 的位置有关,它位于其自己的父 div 的绝对中间和中心。如果我将模态从 div 中取出,它会像我需要的那样全屏打开。

<div id="parent1" style="position:relative;height:100%;z-index:1;">
  <div id="parent2" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;width:100%;z-index:2;">
    (modal, which is set to z-index:3)
  </div>
</div>

标签: htmlcss

解决方案


您已将absolutediv 包裹在位置relativediv 中。这就是为什么它在里面。下面的片段将告诉您定位如何协同relative工作absolute

  .top {
  top: 50px;
  height: 100%;
  position: relative;
}

.relative {
  background: #dfdfdf;
  ) body {
    height: 100%;
  }
  .absolute {
    position: absolute;
    bottom: 0;
  }
<div class="relative top">
  <div class="absolute bottom">hey there</div>
</div>

div 应该一直向下,但是没有,因为它被一个相对的 div 包裹,如果你删除相对类,那么 div 就会掉下来。
对于覆盖整个页面的模态,使用位置fixedabsolute在任何relativediv 之外,甚至更好 -> 使用 flexbox 来实现“非常响应”的模态

document.getElementById('modal-Opener').onclick = function() {
  document.querySelector('.modal').classList.add("modalOpen");
}
body,
html {
  height: 100%
}

.modal {
  border-radius: 20px;
  height: 100px;
  background-color: #dfdfdf;
  width: 60%;
  color: #000;
  padding: 20px;
  display: none;
  position: relative;
  justify-content: center;
  -webkit-animation-name: animatetop;
  -webkit-animation-duration: 0.4s;
  animation-name: animatetop;
  animation-duration: 0.4s align-items:center;
}

.modalOpen {
  display: flex;
}

.flex {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  align-self: center;
}

@-webkit-keyframes animatetop {
  from {
    top: -300px;
    opacity: 0
  }
  to {
    top: 0;
    opacity: 1
  }
}

@keyframes animatetop {
  from {
    top: -300px;
    opacity: 0
  }
  to {
    top: 0;
    opacity: 1
  }
}
<button id="modal-Opener">Open modal</button>
<div class='flex'>
  <div class='modal'>I am a modal</div>
</div>


推荐阅读