即使绝对定位,Z 指数也不起作用



我正在尝试创建一条鱼,即使我正确设置了 z-index 属性,它的后鳍也不会在身体后面。这是怎么回事?我知道我只能将 z-index 与定位元素一起使用。可能影响属性行为的其他因素是什么?

.fish{
margin: auto;
display: block;
margin-top: 5%;
width: 300px;
height: 300px;
}
.fish-body {
position: relative;
top: 40%;
left: 23.5%;
background: black;
width: 53%;
height: 45%;
border-radius: 10% 150% 2% 150%;
transform: rotate(142deg);
}
.backfin-top{
position: absolute;
top: 88%;
left: 56%;
background:yellow;
width: 53%;
height: 45%;
transform: rotate(85deg);
border-radius: 0% 50% 400% 10%;
z-index:-1;
}
.backfin-bottom{
position: absolute;
bottom: 0%;
right: -34%;
background: yellow;
width: 53%;
height: 45%;
border-radius: 10% 400% 10% 50%;
z-index:-1;
}
<div class="fish">
<div class="fish-body">
<div class="backfin-top"></div>
<div class="backfin-bottom"></div>
</div>   
</div>

这是我的解决方案,

基本上,我不得不更改您的 html 结构。下面的检查代码段

这是必需的,因为首先,

<div class="backfin-top"></div>
<div class="backfin-bottom"></div>

将在屏幕上绘制,然后绘制鱼体

在您的情况下,将鳍放在鱼体内div对于将鱼鳍放在鱼后面z-index毫无用处。

在以下示例中z-index不需要将鳍片放在后面。

.fish {
margin: auto;
display: block;
margin-top: 5%;
width: 300px;
height: 300px;
position: relative;
}
.fish-body {
position: relative;
top: 40%;
left: 23.5%;
background: black;
width: 53%;
height: 45%;
border-radius: 10% 150% 2% 150%;
transform: rotate(142deg);
}
.backfin-top {
position: absolute;
top: 38%;
left: -4%;
background: yellow;
width: 33%;
height: 25%;
transform: rotate(217deg);
border-radius: 0% 50% 400% 10%;

}
.backfin-bottom {
position: absolute;
bottom: 15%;
right: 70%;
background: yellow;
width: 33%;
height: 25%;
border-radius: 10% 400% 10% 50%;
transform: rotate(317deg) scale(-1, -1);
}
<div class="fish">
<div class="backfin-top"></div>
<div class="backfin-bottom"></div>
<div class="fish-body">
</div>
</div>

z-index定位的元素上,transform本身在元素上创建新的"堆叠上下文"。 这是怎么回事:

您的.fish-body元素transform设置为"无"以外的其他内容,这为其提供了自己的堆叠上下文。

然后添加一个fins,它是.fish-body的子项。 此子项具有z-index: -1,在.fish-body的堆叠上下文中设置fins的堆栈级别z-index: -1fins不会将其置于.fish-body后面,因为z-index仅在给定的堆叠上下文中有意义。

当您从.fish-body中删除transform时,它会删除其堆叠上下文,导致.fish-body.fins共享堆栈上下文(<html>的堆栈上下文(,并使fins落后于.fish-body

索引在您的情况下不起作用,因为我们无法覆盖父div 的 z 索引。如果我们想使用 z-index,那么所有元素都应该是同一父元素的子元素,我们也应该使用 position。请查看以下代码和输出。

.fish{
margin: auto;
display: block;
margin-top: 5%;
width: 300px;
height: 300px;
position: relative;
}
.fish-body {
position: relative;
top: 40%;
left: 23.5%;
background: black;
width: 53%;
height: 45%;
border-radius: 10% 150% 2% 150%;
transform: rotate(142deg);
}
.backfin-top {
position: absolute;
top: 45%;
left: 0;
background: yellow;
width: 40%;
height: 25%;
transform: rotate(225deg);
border-radius: 0 50% 400% 10%;
z-index: -1;
}
.backfin-bottom {
left: 0;
position: absolute;
bottom: 46px;
background: yellow;
width: 40%;
height: 25%;
border-radius: 10% 400% 10% 50%;
z-index: -1;
transform: rotate(135deg);
}
<div class="fish">
<div class="fish-body"></div>
<div class="backfin-top"></div>
<div class="backfin-bottom"></div>

</div>

最新更新