在堆叠上下文中插入元素及其DOM子元素及其DOM孙子

时间:2016-04-08 13:19:22

标签: html css z-index

如何在其子孙及其孙子之间插入元素? 我有这样的标记:

<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-容器
  2. IMG
  3. 现在如何运作: Wrong

    预期如何运作: Right

    (感谢@ ralph.m的图片)

2 个答案:

答案 0 :(得分:2)

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

#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>

答案 1 :(得分:1)

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

&#13;
&#13;
#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;
}
&#13;
<div id="main">
    <div id="img-container">
        <img id="img" src="https://unsplash.it/400/200">
    </div>
</div>
&#13;
&#13;
&#13;