In your example, you have two scenarios, name them Blue and Blue-2.
In blue, you have two stack contexts, the first contains #blue , and the second contains #red and #green . #blue is in its own stacking context, because z-index: auto , and this context is just part of the default stack.
In Blue-2, you defined z-index: 0 for #blue , so it is part of the same stacking context as #red . In Blue-2, #blue first drawn because it has the lowest index z, 0. However, #green is a child of #blue and drawn over #blue , the parent and child elements form a new styling context (if you wish). Finally, #red painted on the blue-green stack, because the red z-index is 2, which is more than the blue z-index 0. In this case, the green z-index affects the level of its stacking, taking into account blue and any other child elements in #blue . There are three stacking contexts in Blue-2: the default (# 1), one for red and blue (# 2), and the other blue and green (# 3).
Key points
z-index: auto does not start adding a positional element to the new stacking context, whereas z-index: 0 does. Remember that there is at least one stacking context, the default one that is defined for elements due to their natural HTML / DOM order on the page.
Note. . I allowed to describe the markup position as if you had two web pages: one with #red , #blue , #green , and the second with #red2 , #blue2 , #green2 . In fact, since all divs are on the same page, all stacking levels contain all the elements. When there are two red #red2 on the same stack, #red2 will be drawn above #red , since elements located further in the DOM tree will be drawn on top of earlier elements.
Link
I found the following readable enough:
https://developer.mozilla.org/en-US/docs/CSS/Understanding_z-index/Stacking_context_example_2
If you want more information, try looking at:
http://www.w3.org/TR/CSS21/zindex.html