欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何提升当前元素的层级地位

最编程 2024-07-26 15:38:30
...
<style>
    div {
        width: 200px;
        line-height: 200px;
        text-align: center;
        color: #fff;
    }
    .box1 {
        position: absolute;
        top: 0;
        left: 10px;
        background-color: red;
    }
    .box2 {
        position: absolute;
        top: 50px;
        left: 60px;
        background-color: blue;
    }
    .box3 {
        position: absolute;
        top: 90px;
        left: 110px;
        background-color: purple;
    }
</style>
<body>
    <div class="box1">第一个盒子</div>
    <div class="box2">第二个盒子</div>
    <div class="box3">第三个盒子</div>
</body>

上述代码设置了三个绝对定位的盒子,得到的结果如下图:

通过图片可以可以看出,三个盒子的叠放顺序完全是按照html结构里书写的顺序来的,第一个盒子在最下方,第二个盒子在中间,第三个盒子在最上面。

那么此时如果我想改变三个盒子的叠放顺序的话,有两种方法:

第一种:更改html里的书写顺序,麻烦,不推荐;

第二种:使用z-index属性提高对应盒子的层级。比如此处我想把第二个盒子放在最上面第一个盒子放在中间,第三个盒子放在最下面,那么我们只需在上面的代码中给第一个盒子增加一行代码z-index:1;给第二个盒子增加一行代码z-index:2;   即可得到下图的效果(为了方便观察,给盒子增加了透明属性opacity,这个属性的值处于0-1之间,越小越透明,0为完全透明,1为完全不透明)。

<style>
    div {
        width: 200px;
        line-height: 200px;
        text-align: center;
        color: #fff;
    }
    .box1 {
        position: absolute;
        top: 0;
        left: 10px;
        background-color: red;
        z-index: 1;   /* 提高层级*/
        opacity: .5;  /* 设置透明度*/
    }
    .box2 {
        position: absolute;
        top: 50px;
        left: 60px;
        background-color: blue;
        z-index: 2;  /* 将层级提高到最高*/
        opacity: .5; /* 设置透明度*/
    }
    .box3 {
        position: absolute;
        top: 90px;
        left: 110px;
        background-color: purple;
    }
</style>
<body>
    <div class="box1">第一个盒子</div>
    <div class="box2">第二个盒子</div>
    <div class="box3">第三个盒子</div>
</body>

 当然z-index属性后面的数字不是只能写我上面说的1和2.

它的原理是这样的,z-index的数值可以是正整数、负整数或 0,默认值为0,并且值越大,它的层级性越高(即越上),所以只要第二个盒子的z-index的值最大,就会在最上面第一个盒子的z-index的值小于第二个盒子的z-index的值,并且大于第三个盒子就可以处于中间。当然我们一般位于最下面的就不再额外添加z-index属性了,所以默认为0.

推荐阅读