z-index 堆叠顺序问题

z-index stacking order issue

我已经在此处检查了所有类似问题的答案并在网上搜索 - 我已经阅读了所有关于堆叠顺序的教程 - 但我仍然有问题。 我想将一个元素堆叠在另一个元素之上,但无法按我想要的方式堆叠。 这是元素的基本 HTML 和 CSS 结构:

#element-1{
   position: relative;
   z-index: 2 !important;
}
#element-2{
   position: relative;
   display: flex;
   justify-content: center;
   z-index: 1;
}
<div id='element-1'>
   <p>stuff in here</p>
</div>
<div id='element-2'>
   <p>stuff in here2</p>
</div>

因此,如您所见,我试图将元素 1 堆叠在元素 2 之上,但它就是行不通。

CSS top, left, background-color 仅用于演示目的。

#element-1 高于 #element-2 橙色高于绿色导致更高 z-index

#element-1{
    position: absolute;
    z-index: 2;

    /* next properties are only for demonstration purposes but not needed */
    top: 0;
    left: 0;
    background-color: orange;
}
#element-2{
    position: absolute;
    display: flex;
    justify-content: center;
    z-index: 1;
 
     /* next properties are only for demonstration purposes but not needed */
    top: 20px;
    left: 20px;
    background-color: green;
}
<div id='element-1'>
    <p>stuff in here</p>
</div>
<div id='element-2'>
    <p>stuff in here</p>
</div>

#element-2 高于 #element-1 绿色高于橙色原因 z-index

#element-1{
    position: absolute;
    z-index: 1;

    /* next properties are only for demonstration purposes but not needed */
    top: 0;
    left: 0;
    background-color: orange;
}
#element-2{
    position: absolute;
    display: flex;
    justify-content: center;
    z-index: 2;
 
     /* next properties are only for demonstration purposes but not needed */
    top: 20px;
    left: 20px;
    background-color: green;
}
<div id='element-1'>
    <p>stuff in here</p>
</div>
<div id='element-2'>
    <p>stuff in here</p>
</div>

这个答案很奇怪:

将 'element-2' 上的 z-index 设置为 0。

这是一个奇怪的问题,可能不会出现在其他人身上,但我还是会解决的。

我已将 'element-2' 的 z-index 设置为 1,因为我需要在网站的桌面版本上使用它。它里面有链接,如果没有 z-index,这些链接就无法工作。后来我需要对网站进行修改,在进行更改时,我检查了网站移动版本上的弹出式导航菜单 - 这是 'element-1' - 它不会位于 [=21= 前面].我刚刚再次检查了该站点,当我将 'element-2' 的 z-index 设置为 1 时,它位于 'element-1' 的前面。如果我完全删除 'element-2' 的 z-index,它将无法在桌面版本上正常工作,因此解决此特定问题的方法是:

#element-2{
  z-index: 0;
}

感谢阅读。