css z-Index 详解--子元素盖在父元素的兄弟元素上

前置知识

        1、z-index 只有在定位元素上才会生效(即非static定位的元素上)

        2、同级元素,无论是z-index 相同还是没设置。后面的元素层级比前面

        3、元素上有 transform 属性 z-index 会失效

dom结构如下

 // dom部分
<div>
      <div id="box1">
        A
        <div style="z-index: 5; position: relative">
          <p class="a-son">A ---- son</p>
        </div>
      </div>
      <div id="box2">
        B
        <!-- <p class="b-son">B - son</p> -->
      </div>
 </div>

验证第二条



// css 部分
    #box1,
      #box2 {
        position: absolute;
        width: 600px;
        height: 200px;
        color: white;
        z-index: 10;
      }

   .a-son {
        background-color: blueviolet;
        position: absolute;
        height: 150px;
        z-index: 999;
        margin-left: 50px;
      }

需求:把B盖在A上面,A的孩子盖在B上面

我们把同级的父元素z-index 设置为10,注意dom结构 B在A后面,效果如下:

A的孩子并没有,盖在B上。

想要处理这种情况, A,B 都不要设置z-index即可

 #box1,
 #box2 {
     position: absolute;
     width: 600px;
     height: 200px;
     color: white;
     /* z-index: 10; */
  }

验证第三条

 #box1,
 #box2 {
        position: absolute;
        width: 600px;
        height: 200px;
        color: white;
        /* z-index: 10; */
  }

  #box1 {
        background-color: black;
        transform: translateX(10px);
   }

会破坏A的层级,导致B的层级比A高(此时A,B 都没有设置z-index),

但是如果此时我们设置了A的z-index,则A依然会盖在B上

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值