面试官:层叠上下文是什么鸭?

862 阅读1分钟

其实在页面渲染时,渲染过程划分的细一点,会有一个根据层叠上下文分层渲染的过程。那么什么是层叠上下文呢?

dom元素z轴判断顺序

层叠顺序:同一层叠上下文内:z-index > 0 → z-index:0,z-index:auto→inline/inline-block盒子→float浮动盒子→block块级盒子→z-index<0 这样排列的

如何产生层叠上下文

1.html中的根元素html本身就具有层叠上下文,称为根层叠上下文
2.普通元素的position属性非static,并设置z-index属性,产生层叠上下文
3.css3的新属性也产生层叠上下文

例子

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    
    <style>
        .box1,
        .box2 {
            width: 100px;
            height: 100px;
            position: relative;
        }

        .box1 {
            z-index: 2;
        }

        .box2 {
            z-index: 1;
        }

        .a,
        .b,
        .c {
            position: absolute;
            font-size: 20px;
            width: 100px;
            height: 100px;
        }

        .a {
            background-color: blue;
            z-index: 100;
        }

        .b {
            background-color: green;
            top: 20px;
            left: 20px;
            z-index: 200;
        }

        .c {
            background-color: red;
            top: -20px;
            left: 40px;
            z-index: 9999;
        }
    </style>
</head>

<body>
   
    <div class="box1">
        <div class="a">a</div>
        <div class="b">b</div>
    </div>

    <div class="box2">
        <div class="c">c</div>
    </div>
</body>

</html>

虽然c的z-index为9999,但是父盒子box1、box2对比,box1的层级高于box2,所以c在a,b的下面。

image.png


记录记录!