繁体   English   中英

使用z-index堆叠伪元素

[英]stacking pseudo-elements with z-index

我无法使用CSS z-index正确堆叠我的div。 在我的代码中,如果我将.nose::before.nose::afterz-index: -1 ,它会将两个div放在堆栈的最后面。 但是,我只是将这些div放在.nose div后面。 这是我的代码:

 *, *::after, *::before { box-sizing: border-box; margin: 0; padding: 0; } html, body { height: 100%; } body { background: #44BBA4; } .head { position: absolute; margin: auto; top: 0; right: 0; bottom: 0; left: 0; height: 375px; width: 400px; background: #df9e27; border-radius: 50%; border: 10px solid #000; } .head::before, .head::after { content: ""; position: absolute; height: 90px; width: 90px; background: #df9e27; border-radius: 50%; border: 10px solid #000; z-index: -1; } .head::before { top: -30px; left: 40px; } .head::after { top: -30px; right: 40px; } .eye { position: absolute; top: 150px; height: 25px; width: 25px; background: #000; border-radius: 50%; } .eye.left { left: 90px; } .eye.right { right: 90px; } .eye::before { content: ""; position: absolute; top: -50px; left: -37px; height: 100px; width: 100px; border-radius: 50%; border: 12px solid transparent; border-top: 12px solid #000; } .nose { position: absolute; margin: auto; right: 0; left: 0; bottom: 130px; height: 30px; width: 30px; background: #000; border-radius: 50%; } .nose::before, .nose::after { content: ""; position: absolute; height: 68px; width: 73px; background: #fff; border-radius: 50%; border: 10px solid #000; z-index: -1; } 
 <div class="head"> <div class="eye left"></div> <div class="eye right"></div> <div class="nose"></div> </div> 

简而言之:在头部元素上设置z-index。 将耳朵移出头部元件。

这就是原因。

z-index具有堆叠上下文。 每个上下文都有一个根元素(只是任何html元素)。 现在,要成为根元素,它必须遵守以下任何规则:

  • <html>元素
  • static和z-index以外的位置而不是auto
  • 不透明度小于1

因此,默认堆叠上下文以<html>元素作为根。

一旦元素在范围内(换句话说,根元素的子元素),它只能相对于范围内的元素定位。

将其视为嵌套列表。

z-index范围列表

这里包装是一个根元素,因为它的位置设置为relative,z-index为1.并且它的所有子节点现在位于堆叠范围内,Wrap为根。

因此,就像在嵌套列表中一样,特定元素的子元素不能出现在它的根之前。 例如, Child2不能出现在Wrap之前,因为它的范围在它内部。 但它可以出现在Child1之前。

现在,在您的情况下,结构如下:

在此输入图像描述

请注意,头部不是根,因为它不符合成为一个的规则(定位元素也必须具有除auto之外的z-index)。 因此,当你得到这个时,将z-index为-1分配给Nose :: before和::

在此输入图像描述

这些元素一直位于Head后面,因为它们处于相同的堆叠范围内。 但它们出现在Head::before ,因为当元素具有相同的z-index时,它们根据html中的外观顺序堆叠。

现在,为了防止头部孩子出现在它后面,你必须添加z-index。 这将使其成为新堆叠范围的根元素。

在此输入图像描述

但这会产生另一个问题。 现在耳朵位于头顶。 单独使用css是不可能解决的,因为它们位于头部的堆叠范围内。 根总是落在每个孩子身后。

要解决它,你必须将耳朵移出头部。 所以,这意味着,你将无法再使用伪元素(之前和之后)。 我建议在头部之外创建耳朵元素并将所有内容包装在一些其他元素(名为bear?)中,并且位置相对。 如果你仍然想要相对于头部定位耳朵,则需要包装器。

答案主要受本文的启发。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM