CSS z-index 未按预期工作

CSS z-index not working as expected

我最近开始学习 CSS3 动画,我构建了一个小页面来测试这些动画。但是我遇到了关于 z-index 的问题。在我的测试页面中,左下角有一个岛,window 底部有两个波浪。参见 here

我想把岛放在两个波浪之间,但它没有发生。 HTML结构是这样的:

<div class="seashore">
    ...
    <img class="island" src="img/island.png" />
</div>

<div class="sea">
    <img class="wave1" src="img/w1.png" />
    <img class="boat" src="img/tboat.png" />
    <img class="wave2" src="img/w2.png" />
</div>

和各自的CSS

/* Some CSS */

.seashore {
    position: absolute;
    left:0%;
    bottom: 0%;
    width: 50%;
    height: 600px;
    z-index:990;
    overflow: hidden;
}

.island {
    position: absolute;
    left: -1px;
    bottom: 5%;;
    z-index: 1002;
}

.sea {
    position: fixed;
    bottom: 0px;
    width: 90%;
    height: 60px;
    z-index:980;
    ....
}

.wave1 {
    position: absolute;
    top:0px;
    left: 10px;
    z-index: 1000;
    ....
}

.wave2 {
    position: absolute;
    top: 8px;
    left: -16px;
    bottom: -3%;
    z-index: 1004;
    ....

}

.boat {
    position: fixed;
    bottom: -15%;
    left: 75%;
    /*-webkit-transform: rotate(45deg);
    transform: rotate(45deg);*/
    z-index: 1003;
    ....
}

z-index 的顺序是:
大海 (980) < 海岸 (990) < Wave1(1000) < Island(1002) < Boat(1003) < Wave2(1004)

我觉得这可能是因为 waves 和 island 都包含在不同的父容器中。但是由于两个容器的 z-index 都设置为最低,我认为它应该可以工作。

所以我的问题是这种行为的原因是什么?有什么解决方法吗?

如能提供参考资料最好。谢谢。

您需要将元素包含在同一个 div 中,现在您将海岸和海洋分开,因此每个元素中的 z-index 有效 ​​"restarts"。

海滨的 z-index 为 909,从那个社交气球和岛屿有 991 和 1002(他们可能只有 1 和 2),因为它来自海滨的 909。

与海一样,你从 980 开始,然后波浪 1 是 1000,船是 1003,波浪 2 是 1004(它们可能分别是 1、2 和 3)。

只需将所有移动元素放在同一个 div 中,并为每个元素提供一个增量 z-index,使它们处于页面的正确级别。

试着看看 Philip Walton 的文章 What No One Told You About Z-Index

删除 .sea 的 CSS 并更新波浪的 positionz-index:

.wave1 {
    position: absolute;
    bottom:0px;
    left: 10px;
    z-index: 900;
    ....
}

.wave2 {
    position: absolute;
    bottom: 8px;
    left: -16px;
    bottom: -3%;
    z-index: 1003;
}

如上面的答案所述,您可以只使用 1,2 和 3 来表示 z-index

结果: