子元素的 Z-Index 问题

时间:2020-12-25 06:24:08

标签: css

我在一个页面中有兄弟 div,我们称它们为父级。这些父母各有一个孩子的 div。您可以将这些子 div 视为自定义工具提示。默认情况下,子 div 是隐藏的。当我悬停其中一位父母时,它的子 div 变得可见。

由于绘制顺序,当我悬停第一个父级时,它的子级在页面上最后绘制的第二个父级下方可见。所有父级都有相同的 z-index,即 1,所有子 div 的 z-index 都相同,即 2。

所有子 div 都需要绘制在顶部。我如何覆盖它才能像这样工作?

您可以在下面找到可重现的我的问题:

.parent{
    position: relative; height: 200px; width: 200px; z-index: 1; display: inline-block;
}
.parent:hover .child{
    display: block;
}
.child{
    position: absolute; height: 50px; width: 50px; z-index: 2; display: none;
}
 <div class="parent" style="background-color: hotpink;">Parent 1<div class="child" style="background-color: yellow; margin-left: 180px; margin-top: 50px;">Child 1.1</div></div>
 <div class="parent" style="background-color: green;">Parent 2<div class="child" style="background-color: greenyellow; margin-left: -30px;">Child 2.1</div></div>

2 个答案:

答案 0 :(得分:3)

发生这种行为的主要原因是:

<块引用>

Parent1 中的子元素的堆叠顺序低于 Parent Element 2。

尽管在第一个 Parent 中的第一个孩子的 z-index 为 2 的第一个外观中可能会出现,但这是关于 ParentElement1 而不是 ParentElement2。

让我举个演示例子:

.content { 
   position: relative; 
   z-index: 1; 
   background:orange;
   height:400px;
   width:400px;
} 

.child { 
   position: absolute; 
   z-index: 100; 
   background:green;
   height:200px;
   width:200px;
   bottom:0;
   left:0;
} 

.side-tab { 
   position: absolute; 
   z-index: 5; 
   background:teal;
   height:300px;
   width:300px;
   top:10px;
}
<section class="content">            
    <div class="child"></div>
</section>

<div class="side-tab"></div>

查看标记,我们可以看到 content 和 side tab 元素是兄弟元素。也就是说,它们存在于标记中的同一级别(这与 z-index 级别不同)。而子div是内容元素的子元素。

Because the child is inside the content element, its z-index of 100 only has an effect inside its parent, the content element.

But the z-index value of child element doesn't mean anything outside the parent, because the parent content element has its z-index set to 1.

So its children, including the child, can’t break out of that z-index level.

解决方案: 这个问题有两种解决方案。

  1. 从内容中去除定位,这样就不会限制孩子的 z-index。

因此,在您的示例中,如果您删除 position:relative 来自父级,这将解决问题。

.parent{
    position: static; height: 200px; width: 200px; display: inline-block; // Removed position:relative from here
}

由于父元素现在是 unpositioned,它将不再限制 child's z-index 值。

  1. 将子级移出父级,进入主级 页面的堆叠上下文。 (但这会给您带来麻烦,因为您将需要更改标记)

希望这涵盖了我们在 z-index 中面临的定位问题。

答案 1 :(得分:1)

删除.parent的{​​{1}}

 z-index: 1
.parent{
    position: relative; height: 200px; width: 200px; display: inline-block;
}
.parent:hover .child{
    display: block;
}
.child{
    position: absolute; height: 50px; width: 50px; z-index: 2; display: none;
}