【问题标题】:I have position but z index is not working我有位置,但 z 索引不起作用
【发布时间】:2018-07-30 22:59:34
【问题描述】:

我希望外环位于圆圈后面,但是当我尝试使用 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>

【问题讨论】:

    标签: html css z-index


    【解决方案1】:

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

    :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:auto”或“z-index:0”的定位后代,按树顺序排列。对于那些使用 'z-index: auto' 的元素,将元素视为创建了新的堆叠上下文,但任何定位的后代和实际创建新堆叠上下文的后代都应视为父堆叠上下文的一部分强>,不是这个新的。对于那些使用“z-index: 0”的人来说,处理原子生成的堆叠上下文。
      2. 所有不透明度小于 1 的不透明度后代,按照树形顺序创建一个原子生成的堆叠上下文。
      3. 所有具有非无变换的变换后代,按树形顺序创建原子生成的堆叠上下文

    所以这里的技巧是避免定位的伪元素属于其父堆叠上下文,以便能够将其放置在考虑上层堆叠上下文的情况下,从而可以将其放置在在其父级之后。。 p>

    所以父元素不应该指定z-index,不透明度小于1,使用transform

    Full list of the properties that create stacking context.

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多