Positioned elements with a z-index value other than “auto” and elements with an opacity value less than 1 generate a stacking context. Refer to the rules regarding the painting order.
In your first example we have the root stacking context with various descendants including:
- positioned green box with positive z-index
- positioned blue box with
auto
z-index
The blue box with auto
z-index is placed behind; green box with positive z-index is placed in front (see rule no. 8 and 9).
In your second example we have:
- an element with opacity (which contains green box; note that z-index on the green box becomes local to this element)
- positioned blue box without z-index
Both elements fall under same category (see rule no. 8). In which case the HTML order determines which element appear in front. The blue box appears later in the source order so it appears in front.