Z-Index Relative or Absolute?

前端 未结 4 676
野性不改
野性不改 2020-11-27 02:30

I\'m trying to find an answer to the following question:

Is an element\'s z-index style its absolute stack order, or its stack order relative to its parent?

4条回答
  •  悲&欢浪女
    2020-11-27 03:13

    z-index is relative. See this detailed answer, which I wrote for a similar question.

    If none of the other elements have a defined z-index, using z-index: 1 will be fine.

    Model: How is the z-index determined?

                                             z-index
    
    Auto 1
    Auto 1.1
    Manual 1
    Auto 1.1.2
    Auto 1.2
    Auto 2

    First, the direct child nodes of the body are walked through. Two elements are encountered: #A and #F. These are assigned a z-index of 1 and 2. This step is repeated for each (child) element in the document.

    Then, the manually set z-index properties are checked. If two z-index values equal, their position in the document tree are compared.

    Your case:

    Z-index 1
    Z-index 3
    Z-index 2

    You'd expect #Y to overlap #Z, because a z-index of 3 is clearly higher than 2. Well, you're wrong: #Y is a child of #X, with a z-index of 1. Two is higher than one, and thus, #Z will be shown over #X (and #Y).

    Here is a plunker to visualize this a little better, or try the snippet below ,

    .redbox,
    .greenbox,
    .bluebox {
      height: 100px;
      width: 100px;
      position: relative;
      color: #fff;
      padding: 3px;
    }
    
    .redbox {
      background: red;
      z-index: 1;
    }
    
    .greenbox {
      background: green;
      top: 40px;
      left: 40px;
      z-index: 3;
    }
    
    .bluebox {
      background: blue;
      top: -20px;
      left: 20px;
      z-index: 2;
    }
    z: 1
    z: 3
    z: 2

提交回复
热议问题