如何在不向下推页面其余部分的情况下显示模式?

How to make a modal appear without pushing the rest of the page down?

当我通过 javascript 激活 .hidden class 时,我希望模式位于页面的中心并出现在 .main 的顶部。 但是,当我启用 .hidden class 时,.main 会被下推,即使我已经为 .modal 提供了更高的 z-index。

我做错了什么?

https://codepen.io/boatus/pen/abWxzwL

           .modal {
          background-color: rgb(162, 154, 170);
          width: 70vw;
          height: 70vh;
           margin: auto;
         position: relative;
        z-index: 2;
         } 

          .main {
            display: flex;
           justify-content: center;
            margin: 40px;
          gap: 100px;
         z-index: 1;
       }

您必须使用位置 absolute

而不是位置 relative

简单地将此 css 添加到您的 .modal class:

 position: absolute;
  left:50%;
  top:50%;
  transform:translate(-50%,-50%);