Difference between auto, 0, and no z-index?

前端 未结 5 764
温柔的废话
温柔的废话 2021-02-11 17:12

What is the difference between:

  1. z-index: auto
  2. z-index: 0
  3. no z-index at all

All the above sc

5条回答
  •  眼角桃花
    2021-02-11 17:42

    What @BoltClock said is right.

    Not specifying z-index is the same as z-index: auto; that is its initial value.

    About z-index: 0 it's important to note the following:

    z-index: 0 creates a stacking context while z-index: auto do not. You can check MDN for more information about this.

    In most cases this won't affect the rendered elements.

    The following fiddle is an example where it matters: https://jsfiddle.net/ramcdvns/3/

    Code and explanation below:

    
    
    

    In both examples, red and blue are siblings with a position: relative and green is a child of red with position: relative and z-index: 1:

    • Root
      • Red: position: relative
        • Green: position: relative; z-index: 1
      • Blue: position: relative

    In the first example, green will be positioned above red and blue. This is because it has a z-index: 1, so a stacking context is created and put above the root context.

    In the second example, green will be positioned above red, but below blue. This is because red has z-index: 0, so it creates a stacking context at the same level of blue. So green will be above red (because green also creates a stacking context), but below blue because it's trapped in the context of red.

    Hopefully the fiddle is clear enough as it's hard to explain this in words.

提交回复
热议问题