我有位置,但是z索引不起作用

时间:2018-07-30 22:59:34

标签: html css z-index

我希望外圈在圆环后面,但是当我尝试使用z-index时,它不起作用。什么也没做我做了2个环,一个环在圆圈的顶部,没有顶部,另一个环在圆圈的后面,我只是无法移动,我也不知道为什么。

:root{
  --size:200px;
}
#background {
  width:100%;
  height:100%;
  position:absolute;
  top:0;
  left:0;
  background: linear-gradient(-23.5deg, #000033, #00001a);
  z-index:-2;
}

#background #mainplanet {
  width:var(--size);
  height:var(--size);
  background:#fff;
  position:relative;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
  border-radius:50%;
}

#background #mainplanet:before,#background #mainplanet:after{
  content:"";
  width:calc(var(--size) * 1.5);
  height:calc(var(--size) / 2);
  border:30px solid #000;
  position:absolute;
  top:10px;
  left:-80px;
  border-radius:50%;
  transform: rotateX(66deg) rotateY(170deg);
}

#background #mainplanet:before{
  border-top-color:transparent;
}

#background #mainplanet:after{
  z-index:-3;
}
<div id="background">
  <div id="mainplanet">
  </div>
</div>

1 个答案:

答案 0 :(得分:4)

您需要删除转换并将其替换为其他内容,然后才能将伪元素移到后面:

:root{
  --size:200px;
}
#background {
  width:100%;
  height:100%;
  position:absolute;
  top:0;
  left:0;
  background: linear-gradient(-23.5deg, #000033, #00001a);
  z-index:-2;
}

#background #mainplanet {
  width:var(--size);
  height:var(--size);
  background:#fff;
  position:relative;
  top:calc(50% - var(--size)/2);
  left:calc(50% - var(--size)/2);
  border-radius:50%;
}

#background #mainplanet:before,#background #mainplanet:after{
  content:"";
  width:calc(var(--size) * 1.5);
  height:calc(var(--size) / 2);
  border:30px solid #000;
  position:absolute;
  top:10px;
  left:-80px;
  border-radius:50%;
  transform: rotateX(66deg) rotateY(170deg);
}

#background #mainplanet:before{
  border-top-color:transparent;
}

#background #mainplanet:after{
  z-index:-3;
}
<div id="background">
  <div id="mainplanet">
  </div>
</div>

我们可能会在the specification中看到:

  
      
  1. 所有已定位,不透明或变换后代,按树顺序分为以下几类:      
        
    1. 所有定位的后代,其“ z-index:自动”或“ z-index:0”以树顺序排列。对于具有“ z-index:auto”的元素,将其视为已创建新的堆栈上下文,但任何定位的后代和实际创建新堆栈上下文的后代都应视为父级堆栈上下文的一部分,而不是这个新的。对于那些“ z-index:0”的对象,将视为自动生成的堆栈上下文。
    2.   
    3. 所有不透明度小于1的不透明度后代,以树顺序创建原子生成的堆栈上下文。
    4.   
    5. 所有没有树变换的变换子孙,以树顺序创建原子生成的堆叠上下文
    6.   
  2.   

因此,这里的技巧是避免定位的伪元素属于其父堆栈上下文,从而能够考虑上层堆栈上下文来放置它,从而可以将其放置在其父对象的后面。 >

因此,父元素不应指定z-index,不透明度小于1,请使用transform,等等。

Full list of the properties that create stacking context.