在堆叠上下文中的 DOM child 和它的 DOM 孙子之间插入一个元素

Insert an element between and its DOM child and its DOM grandson in the stacking context

如何在它的 child 和它的孙子之间插入一个元素? 我有这样的标记:

<div id="main">
    <div id="img-container">
        <img id="img">
    </div>
</div>

样式为:

#main {
    margin-top: 300px;
    position: relative;
    z-index: 1;
}
#img-container {
    margin-top: -150px;
    position: relative;
    z-index: 0;
}
#img {
    display: block;
    position: relative;
    z-index: 2;
}

现在的顺序必须是

  1. img-container
  2. 主要
  3. img

现在如何运作:

它的预期工作方式:

(感谢@ralph.m提供图片)

问题不清楚,但您只是在寻找这样的东西吗? (它基本上涉及将 img-container 上的 margin-top 替换为 top。)

#main {
    margin-top: 100px;
    position: relative;
    z-index: 1;
    background: #e7e7e7;
    width: 500px;
    padding: 0 40px;
}
#img-container {
    top: -50px;
    position: relative;
    z-index: 0;
    background: #30373b;
    width: 400px;
    padding: 40px;
}
#img {
    display: block;
    position: relative;
    z-index: 2;
}
<div id="main">
    <div id="img-container">
        <img id="img" src="https://unsplash.it/400/200">
    </div>
</div>

您真的可以获得 视觉效果 效果,而无需重新排序图层等。您可以反转这些元素的样式以获得该外观。或者你可以像这样做更简单的事情:

#main {
    position: relative;
    background: #e7e7e7;
    width: 600px;
    padding: 0 50px;
    margin: 50px;
}

#main::after {
    content: '';
    width: 500px;
    height: 200px;
    position: absolute;
    z-index: -1;
    left:50%;
    margin-left: -250px;
    top: -50px;
    background: #30353b;
}

#img-container {
    position: relative;
    width: 400px;
    top: -20px;
    margin: 0 auto;
}
    <div id="main">
        <div id="img-container">
            <img src="https://unsplash.it/400/200">
        </div>
    </div>