z-index

  • z-index:可以设置元素的叠加顺序,但依赖定位属性。
  • z-index大的元素会覆盖z-index小的元素
  • z-index为auto的元素不参与层级比较
  • z-index为负值,元素被普通流中的元素覆盖

number设置z-index大小,number越大z-index越大。z-index只作用于带有定位属性的元素。如果position属性为static的时候,就相当于没有定位属性。在普通中也有层级关系的。

<style>

        *{
            margin: 0;
            padding: 0;
        }
        .div1{
            width: 100px;
            height: 100px;
            background: red;
            position: relative;
         


        }

        .div2{
            width: 100px;
            height: 100px;
            background: blue;
            position: relative;
            top: -50px;
            
        }


    </style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>

</body>

如果在.div1中加入

z-index: 1;

<style>

        .div1{
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            
        }

        .div2{
            width: 100px;
            height: 100px;
            background: blue;
            position: relative;

        }


    </style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>



</body>

蓝色区域块把红色覆盖了。

原因是absolute没有设置left和top。

设置了之后还是覆盖了:

<style>
        .div1{
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            left: 0;
            top: 0;

        }

        .div2{
            width: 100px;
            height: 100px;
            background: blue;
            position: relative;

        }


    </style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>



</body>

无论是absolute还是relative,层级关系依然是顺序关系。把absolute改成fixed也是这样。

<style>
        .div1{
            width: 100px;
            height: 100px;
            background: red;
            position: relative;


        }

        .div2{
            width: 100px;
            height: 100px;
            background: blue;
            position: relative;
            z-index: 10;

        }
        .per{
            width: 200px;
            height: 200px;
            background: green;
            position: relative;
            z-index: 11;
            top: -50px;
        }
        
        .test{
            width: 100px;
            height: 100px;
            background: #ccc;
            position: relative;
            z-index: 1;
        }


    </style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="per">
    <div class="test"></div>
</div>


</body>

灰色框层级小,但是它显示出来了。受制于父元素的影响的优势,父元素的层级大于相邻元素的层级,无论它的级别有多小,都可以大于相邻的小于父元素的层级。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值