我想看看是否有可能把元素交织在一起。我觉得这根本不可能。唯一需要注意的是b
是a
的子元素,d
是c
的子元素,a
和c
是兄弟元素(几乎html不能更改为业务规则)。
Html格式
<div style="position:relative;margin-top: 50px">
<div class="z a">
<div class="z b"></div>
</div>
<div class="z c">
<div class="z d"></div>
</div>
</div>
CSS
.z{ position: absolute }
.a{ left: 10px; right: 10px; top: 10px; height: 50px; background-color: blue;}
.b{ left: 50px; right: 50px; top: 10px; height: 50px; background-color: red;}
.c{ left: 20px; right: 20px; top: 30px; height: 50px; background-color: green;}
.d{ left: 10px; right: 10px; top: 10px; height: 50px; background-color: purple;}
.a{ z-index: 1;}
.b{ z-index: 2;}
.c{ z-index: 1;}
.d{ z-index: 2;}
JsFiddle Example
实际结果:
预期结果:
最佳答案
z-index
属性相对于元素所属的堆栈上下文设置元素的堆栈级别。
因此,如果你想混合(在z轴)不同元素的孩子,这些父母不可以建立任何堆叠上下文。这样,孩子们将属于同一个堆叠上下文,你将能够使用z-index
命令他们在z轴上。
参见Which CSS properties create a stacking context?了解如何防止元素建立堆栈上下文。其中,它需要默认的position: static
或z-index: auto
和opacity: 1
。
在您的情况下,.b
属于具有z-index: 1
的堆栈上下文。然后,它被下面的叠加上下文的内容重叠,z-index
大于或等于1
,如.c
。将z-index
设置为.b
并不能阻止这一点。如果在z-index
上使用较低的.c
,则其内容(如.d
)将无法重叠。
相反,删除以下内容就足够了:
.a { z-index: 1; }
.c { z-index: 1; }
这样,
.b
和.a
就不会生成任何堆栈上下文,所以您可以随心所欲地为他们的孩子排序。.z{ position: absolute }
.a{ left: 10px; right: 10px; top: 10px; height: 50px; background-color: blue; }
.b{ left: 50px; right: 50px; top: 10px; height: 50px; background-color: red; }
.c{ left: 20px; right: 20px; top: 30px; height: 50px; background-color: green; }
.d{ left: 10px; right: 10px; top: 10px; height: 50px; background-color: purple; }
.b{ z-index: 2; }
.d{ z-index: 2; }
<div style="position:relative;margin-top: 50px">
<div class="z a">
<div class="z b"></div>
</div>
<div class="z c">
<div class="z d"></div>
</div>
</div>